{"text": "/* methods.cpp */\n\n#include \"linalg.h\"\n#include \"methods.h\"\n#include \"structs.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nextern \"C\"\n{\n void _ETS_IK(PyObject *ets, int n, double *q, double *Tep, double *ret)\n {\n // double E;\n double *Te = (double *)PyMem_RawCalloc(16, sizeof(double));\n double *e = (double *)PyMem_RawCalloc(6, sizeof(double));\n\n double *a = (double *)PyMem_RawCalloc(6, sizeof(double));\n // a[0] = 1.0;\n // a[1] = 4.0;\n // a[2] = 2.0;\n // a[3] = 5.0;\n // a[4] = 3.0;\n // a[5] = 6.0;\n a[0] = 1.0;\n a[1] = 2.0;\n a[2] = 3.0;\n a[3] = 4.0;\n a[4] = 5.0;\n a[5] = 6.0;\n double *b = (double *)PyMem_RawCalloc(12, sizeof(double));\n b[0] = 11.0;\n b[1] = 15.0;\n b[2] = 19.0;\n b[3] = 12.0;\n b[4] = 16.0;\n b[5] = 20.0;\n b[6] = 13.0;\n b[7] = 17.0;\n b[8] = 21.0;\n b[9] = 14.0;\n b[10] = 18.0;\n b[11] = 22.0;\n // b[0] = 11.0;\n // b[1] = 12.0;\n // b[2] = 13.0;\n // b[3] = 14.0;\n // b[4] = 15.0;\n // b[5] = 16.0;\n // b[6] = 17.0;\n // b[7] = 18.0;\n // b[8] = 19.0;\n // b[9] = 20.0;\n // b[10] = 21.0;\n // b[11] = 22.0;\n\n // double *U = (double *)PyMem_RawCalloc(16, sizeof(double));\n // double *invU = (double *)PyMem_RawCalloc(16, sizeof(double));\n // double *temp = (double *)PyMem_RawCalloc(16, sizeof(double));\n // double *ret = (double *)PyMem_RawCalloc(16, sizeof(double));\n // Py_ssize_t m;\n int arrived = 0, iter = 0;\n\n while (arrived == 0 && iter < 500)\n {\n // Current pose Te\n // _ETS_fkine(ets, q, (double *)NULL, NULL, Te);\n\n // Angle axis error e\n _angle_axis(Te, Tep, e);\n\n // Squared error E\n // E = 0.5 * e @ We @ e\n // E = 0.5 * (e[0] * e[0] + e[1] * e[1] + e[2] * e[2] + e[3] * e[3] + e[4] * e[4] + e[5] * e[5]);\n }\n\n // _ETS_fkine(ets, q, (double *)NULL, NULL, Te);\n\n // for (int i = 0; i < 2; i++)\n // {\n // for (int j = 0; j < 4; j++)\n // {\n // ret[i * 4 + j] = 0.0;\n // }\n // }\n\n // _mult_T(2, 3, 0, a, 3, 4, 0, b, ret);\n // _mult_T(3, 2, 1, a, 3, 4, 0, b, ret);\n // _mult_T(3, 2, 1, a, 4, 3, 1, b, ret);\n // _mult_T(2, 3, 0, a, 4, 3, 1, b, ret);\n\n // int j = 0;\n }\n\n void _ETS_hessian(int n, MapMatrixJc &J, MapMatrixHr &H)\n {\n for (int j = 0; j < n; j++)\n {\n for (int i = j; i < n; i++)\n {\n H.block<3, 1>(j * 6, i) = J.block<3, 1>(3, j).cross(J.block<3, 1>(0, i));\n H.block<3, 1>(j * 6 + 3, i) = J.block<3, 1>(3, j).cross(J.block<3, 1>(3, i));\n\n if (i != j)\n {\n H.block<3, 1>(i * 6, j) = H.block<3, 1>(j * 6, i);\n H.block<3, 1>(i * 6 + 3, j) = Eigen::Vector3d::Zero();\n }\n }\n }\n }\n\n void _ETS_jacob0(ETS *ets, double *q, double *tool, MapMatrixJc &eJ)\n {\n // ET *et;\n // double T[16];\n // MapMatrix4dc eT(T);\n // Matrix4dc U;\n // Matrix4dc invU;\n // Matrix4dc temp;\n // Matrix4dc ret;\n\n // int j = 0;\n\n // U = Eigen::Matrix4d::Identity();\n\n // // Get the forward kinematics into T\n // _ETS_fkine(ets, q, (double *)NULL, tool, eT);\n\n // for (int i = 0; i < ets->m; i++)\n // {\n // et = ets->ets[i];\n\n // if (et->isjoint)\n // {\n // _ET_T(et, &ret(0), q[et->jindex]);\n // temp = U * ret;\n // U = temp;\n\n // if (i == ets->m - 1 && tool != NULL)\n // {\n // MapMatrix4dc e_tool(tool);\n // temp = U * e_tool;\n // U = temp;\n // }\n\n // _inv(&U(0), &invU(0));\n // temp = invU * eT;\n\n // if (et->axis == 0)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 2) * temp(1, 3) - U(Eigen::seq(0, 2), 1) * temp(2, 3);\n\n // eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 0);\n // }\n // else if (et->axis == 1)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 0) * temp(2, 3) - U(Eigen::seq(0, 2), 2) * temp(0, 3);\n // eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 1);\n // }\n // else if (et->axis == 2)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 1) * temp(0, 3) - U(Eigen::seq(0, 2), 0) * temp(1, 3);\n // eJ(Eigen::seq(3, 5), j) = U(Eigen::seq(0, 2), 2);\n // }\n // else if (et->axis == 3)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 0);\n // eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n // }\n // else if (et->axis == 4)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 1);\n // eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n // }\n // else if (et->axis == 5)\n // {\n // eJ(Eigen::seq(0, 2), j) = U(Eigen::seq(0, 2), 2);\n // eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n // }\n // j++;\n // }\n // else\n // {\n // _ET_T(et, &ret(0), q[et->jindex]);\n // temp = U * ret;\n // U = temp;\n // }\n // }\n\n ET *et;\n Eigen::Matrix tJ(6, ets->n);\n double T[16];\n MapMatrix4dc eT(T);\n Matrix4dc U = Eigen::Matrix4d::Identity();\n Matrix4dc invU;\n Matrix4dc temp;\n Matrix4dc ret;\n int j = ets->n - 1;\n\n if (tool != NULL)\n {\n Matrix4dc e_tool(tool);\n temp = e_tool * U;\n U = temp;\n }\n\n for (int i = ets->m - 1; i >= 0; i--)\n {\n et = ets->ets[i];\n\n if (et->isjoint)\n {\n if (et->axis == 0)\n {\n tJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2)) * U(1, 3) - U(1, Eigen::seq(0, 2)) * U(2, 3);\n tJ(Eigen::seq(3, 5), j) = U(0, Eigen::seq(0, 2));\n }\n else if (et->axis == 1)\n {\n tJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2)) * U(2, 3) - U(2, Eigen::seq(0, 2)) * U(0, 3);\n tJ(Eigen::seq(3, 5), j) = U(1, Eigen::seq(0, 2));\n }\n else if (et->axis == 2)\n {\n tJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2)) * U(0, 3) - U(0, Eigen::seq(0, 2)) * U(1, 3);\n tJ(Eigen::seq(3, 5), j) = U(2, Eigen::seq(0, 2));\n }\n else if (et->axis == 3)\n {\n tJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2));\n tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n else if (et->axis == 4)\n {\n tJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2));\n tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n else if (et->axis == 5)\n {\n tJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2));\n tJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n\n _ET_T(et, &ret(0), q[et->jindex]);\n temp = ret * U;\n U = temp;\n j--;\n }\n else\n {\n _ET_T(et, &ret(0), q[et->jindex]);\n temp = ret * U;\n U = temp;\n }\n }\n\n Eigen::Matrix ev;\n ev.topLeftCorner<3, 3>() = U.topLeftCorner<3, 3>();\n ev.topRightCorner<3, 3>() = Eigen::Matrix3d::Zero();\n ev.bottomLeftCorner<3, 3>() = Eigen::Matrix3d::Zero();\n ev.bottomRightCorner<3, 3>() = U.topLeftCorner<3, 3>();\n eJ = ev * tJ;\n }\n\n void _ETS_jacobe(ETS *ets, double *q, double *tool, MapMatrixJc &eJ)\n {\n ET *et;\n double T[16];\n MapMatrix4dc eT(T);\n Matrix4dc U = Eigen::Matrix4d::Identity();\n Matrix4dc invU;\n Matrix4dc temp;\n Matrix4dc ret;\n int j = ets->n - 1;\n\n if (tool != NULL)\n {\n Matrix4dc e_tool(tool);\n temp = e_tool * U;\n U = temp;\n }\n\n for (int i = ets->m - 1; i >= 0; i--)\n {\n et = ets->ets[i];\n\n if (et->isjoint)\n {\n if (et->axis == 0)\n {\n eJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2)) * U(1, 3) - U(1, Eigen::seq(0, 2)) * U(2, 3);\n eJ(Eigen::seq(3, 5), j) = U(0, Eigen::seq(0, 2));\n }\n else if (et->axis == 1)\n {\n eJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2)) * U(2, 3) - U(2, Eigen::seq(0, 2)) * U(0, 3);\n eJ(Eigen::seq(3, 5), j) = U(1, Eigen::seq(0, 2));\n }\n else if (et->axis == 2)\n {\n eJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2)) * U(0, 3) - U(0, Eigen::seq(0, 2)) * U(1, 3);\n eJ(Eigen::seq(3, 5), j) = U(2, Eigen::seq(0, 2));\n }\n else if (et->axis == 3)\n {\n eJ(Eigen::seq(0, 2), j) = U(0, Eigen::seq(0, 2));\n eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n else if (et->axis == 4)\n {\n eJ(Eigen::seq(0, 2), j) = U(1, Eigen::seq(0, 2));\n eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n else if (et->axis == 5)\n {\n eJ(Eigen::seq(0, 2), j) = U(2, Eigen::seq(0, 2));\n eJ(Eigen::seq(3, 5), j) = Eigen::Vector3d::Zero();\n }\n\n _ET_T(et, &ret(0), q[et->jindex]);\n temp = ret * U;\n U = temp;\n j--;\n }\n else\n {\n _ET_T(et, &ret(0), q[et->jindex]);\n temp = ret * U;\n U = temp;\n }\n }\n }\n\n void _ETS_fkine(ETS *ets, double *q, double *base, double *tool, MapMatrix4dc &e_ret)\n {\n ET *et;\n Matrix4dc temp;\n Matrix4dc current;\n\n if (base != NULL)\n {\n MapMatrix4dc e_base(base);\n current = e_base;\n }\n else\n {\n current = Eigen::Matrix4d::Identity();\n }\n\n for (int i = 0; i < ets->m; i++)\n {\n et = ets->ets[i];\n\n _ET_T(et, &e_ret(0), q[et->jindex]);\n temp = current * e_ret;\n current = temp;\n }\n\n if (tool != NULL)\n {\n MapMatrix4dc e_tool(tool);\n e_ret = current * e_tool;\n }\n else\n {\n e_ret = current;\n }\n }\n\n void _ET_T(ET *et, double *ret, double eta)\n {\n // Check if static and return static transform\n if (!et->isjoint)\n {\n _copy(et->T, ret);\n return;\n }\n\n if (et->isflip)\n {\n eta = -eta;\n }\n\n // Calculate ET trasform based on eta\n et->op(ret, eta);\n }\n\n} /* extern \"C\" */", "meta": {"hexsha": "0d9b8d0ac106b747241d41383ab500c9fcae6e17", "size": 11994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "roboticstoolbox/core/methods.cpp", "max_stars_repo_name": "Russ76/robotics-toolbox-python", "max_stars_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roboticstoolbox/core/methods.cpp", "max_issues_repo_name": "Russ76/robotics-toolbox-python", "max_issues_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roboticstoolbox/core/methods.cpp", "max_forks_repo_name": "Russ76/robotics-toolbox-python", "max_forks_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_forks_repo_licenses": ["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.5969387755, "max_line_length": 123, "alphanum_fraction": 0.3490078373, "num_tokens": 4130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19985351043313856}} {"text": "////////////////////////////////////////////////////////////////////////////////\n// Copyright 2019 FZI Research Center for Information Technology\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,\n// this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n// this list of conditions and the following disclaimer in the documentation\n// and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived from this\n// 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\n//-----------------------------------------------------------------------------\n/*!\\file DampedLeastSquaresSolver.cpp\n *\n * \\author Stefan Scherzinger \n * \\date 2020/03/27\n *\n */\n//-----------------------------------------------------------------------------\n\n// this package\n#include \n\n// Pluginlib\n#include \n\n// other\n#include \n\n/**\n * \\class cartesian_controller_base::DampedLeastSquaresSolver \n *\n * Users may explicitly specify this solver with \\a \"damped_least_squares\" as \\a\n * ik_solver in their controllers.yaml configuration file for each controller:\n *\n * \\code{.yaml}\n * :\n * type: \"\"\n * ik_solver: \"damped_least_squares\"\n * ...\n *\n * solver:\n * ...\n * damped_least_squares:\n * alpha: 0.5\n * \\endcode\n *\n */\nPLUGINLIB_EXPORT_CLASS(cartesian_controller_base::DampedLeastSquaresSolver, cartesian_controller_base::IKSolver)\n\n\n\n\n\nnamespace cartesian_controller_base{\n\n DampedLeastSquaresSolver::DampedLeastSquaresSolver()\n : m_alpha(0.01)\n {\n }\n\n DampedLeastSquaresSolver::~DampedLeastSquaresSolver(){}\n\n trajectory_msgs::JointTrajectoryPoint DampedLeastSquaresSolver::getJointControlCmds(\n ros::Duration period,\n const ctrl::Vector6D& net_force)\n {\n // Compute joint jacobian\n m_jnt_jacobian_solver->JntToJac(m_current_positions,m_jnt_jacobian);\n\n // Compute joint velocities according to:\n // \\f$ \\dot{q} = ( J^T J + \\alpha^2 I )^{-1} J^T f \\f$\n ctrl::MatrixND identity;\n identity.setIdentity(m_number_joints, m_number_joints);\n\n m_current_velocities.data =\n (m_jnt_jacobian.data.transpose() * m_jnt_jacobian.data\n + m_alpha * m_alpha * identity).inverse() * m_jnt_jacobian.data.transpose() * net_force;\n\n // Integrate once, starting with zero motion\n m_current_positions.data = m_last_positions.data + 0.5 * m_current_velocities.data * period.toSec();\n\n // Make sure positions stay in allowed margins\n applyJointLimits();\n\n // Apply results\n trajectory_msgs::JointTrajectoryPoint control_cmd;\n for (int i = 0; i < m_number_joints; ++i)\n {\n control_cmd.positions.push_back(m_current_positions(i));\n control_cmd.velocities.push_back(m_current_velocities(i));\n\n // Accelerations should be left empty. Those values will be interpreted\n // by most hardware joint drivers as max. tolerated values. As a\n // consequence, the robot will move very slowly.\n }\n control_cmd.time_from_start = period; // valid for this duration\n\n return control_cmd;\n }\n\n bool DampedLeastSquaresSolver::init(ros::NodeHandle& nh,\n const KDL::Chain& chain,\n const KDL::JntArray& upper_pos_limits,\n const KDL::JntArray& lower_pos_limits)\n {\n IKSolver::init(nh, chain, upper_pos_limits, lower_pos_limits);\n\n m_jnt_jacobian_solver.reset(new KDL::ChainJntToJacSolver(m_chain));\n m_jnt_jacobian.resize(m_number_joints);\n\n // Connect dynamic reconfigure and overwrite the default values with values\n // on the parameter server. This is done automatically if parameters with\n // the according names exist.\n m_callback_type = boost::bind(\n &DampedLeastSquaresSolver::dynamicReconfigureCallback, this, _1, _2);\n\n m_dyn_conf_server.reset(\n new dynamic_reconfigure::Server(\n ros::NodeHandle(nh.getNamespace() + \"/solver/damped_least_squares\")));\n m_dyn_conf_server->setCallback(m_callback_type);\n return true;\n }\n\n void DampedLeastSquaresSolver::dynamicReconfigureCallback(IKConfig& config, uint32_t level)\n {\n m_alpha = config.alpha;\n }\n\n} // namespace\n", "meta": {"hexsha": "66a6b5321963265b1c504330bdc6a1eb9809c44f", "size": 5588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_stars_repo_name": "graziegrazie/cartesian_controllers", "max_stars_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2019-11-01T07:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:14:52.000Z", "max_issues_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_issues_repo_name": "graziegrazie/cartesian_controllers", "max_issues_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T20:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:17:50.000Z", "max_forks_repo_path": "cartesian_controller_base/src/DampedLeastSquaresSolver.cpp", "max_forks_repo_name": "graziegrazie/cartesian_controllers", "max_forks_repo_head_hexsha": "40156bbbd45de17f0e03e9007863d087295c318f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T07:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:26:35.000Z", "avg_line_length": 37.2533333333, "max_line_length": 112, "alphanum_fraction": 0.6791338583, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1995602419113094}} {"text": "//\n// main.cpp\n// sthlm\n//\n// Created by Jilin Zhang on 2/14/17.\n// Copyright © 2017 Jilin Zhang. All rights reserved.\n//\n\n\n\n#include \n#include \n#include \n#include \"unordered_map\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \"omp.h\"\n#include \"kseq.h\"\n#include \n\nKSEQ_INIT(gzFile,gzread);\n\n//\nstruct Unitscore{\n long count;\n double discore;\n double monoscore;\n};\n\nstd::unordered_map kstore;\n\n\n//g++ -std=c++11 main.cpp -o rmap\n//g++ -std=c++11 main.cpp -o rmap -lboost_program_options -lz\n/*\n basemap[] works by storing a very small array that maps a base to\n its complement, by dereferencing the array with the ASCII char's\n decimal value as the index\n (int) 'A' = 65;\n (int) 'C' = 67;\n (int) 'G' = 71;\n (int) 'T' = 84;\n (int) 'a' = 97;\n (int) 'c' = 99;\n (int) 'g' = 103;\n (int) 't' = 116;\n (int) 'N' = 78;\n (int) 'U' = 85;\n (int) 'u' = 117;\n for example: basemap['A'] => basemap[65] => 'T' etc.\n */\nstatic const char basemap[255] =\n{\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 0 - 9 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 10 - 19 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 20 - 29 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 30 - 39 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 40 - 49 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 50 - 59 */\n '\\0', '\\0', '\\0', '\\0', '\\0', 'U', '\\0', 'G', '\\0', '\\0', /* 60 - 69 */\n '\\0', 'C', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', 'N', '\\0', /* 70 - 79 */\n '\\0', '\\0', '\\0', '\\0', 'A', 'A', '\\0', '\\0', '\\0', '\\0', /* 80 - 89 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', 'u', '\\0', 'g', /* 90 - 99 */\n '\\0', '\\0', '\\0', 'c', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 100 - 109 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', 'a', 'a', '\\0', '\\0', /* 110 - 119 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 120 - 129 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 130 - 139 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 140 - 149 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 150 - 159 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 160 - 169 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 170 - 179 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 180 - 189 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 190 - 199 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 200 - 209 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 210 - 219 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 220 - 229 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 230 - 239 */\n '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', '\\0', /* 240 - 249 */\n '\\0', '\\0', '\\0', '\\0', '\\0' /* 250 - 254 */\n};\n\nvoid fetch_matrix(std::unordered_map > *map, std::string str, int ind, double count);\nvoid show_matrix(std::unordered_map > *x);\nvoid kmerizing (std::string *id, std::string* seq, int kmer, int gap, std::string* name, std::unordered_map > *map);\ndouble monoscoring(std::string subseq, std::unordered_map > *map, int gap_len=0, int gap_pos=0);\ndouble discoring(std::string subseq, std::unordered_map > *map, int gap_len=0, int gap_pos=0);\ninline double singleStringScore(double x, std::string* s, long p, std::unordered_map > *m);\ninline double pairStringScore(double x, std::string* s, long sp, std::unordered_map > *m);\nvoid Matrixfile(const char*x, std::unordered_map > *y, double pseudo_count);\nint listParser(const char* list_name, std::string* names, int* length, std::unordered_map >* map,double pcount);\nstd::string seq_revcomp(std::string str);\nvoid GenomeMap(std::string *id, std::string *seq, long monoLen, std::string *mname, std::unordered_map >* map );\nvoid hashOut();\nvoid unCenterCorr();\n\n\n\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v){\n copy(v.begin(), v.end(), std::ostream_iterator(os, \" \"));\n return os;\n}\n\nint main(int argc, char * argv[]) {\n \n std::unordered_map > matrixmap[100];\n int motif_len[100];\n std::string names_motif[100];\n double pseudo_count=0.00001;\n int motif_counts=0;\n char list_name[100],fasta_name[100];\n int kmer_length, gap_length;\n bool kmerflag=false ,outflag=false,corrflag=false, revcomflag=false;\n \n \n boost::program_options::options_description desc(\"Allowed options:\");\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"fasta\", boost::program_options::value(), \"input sequence file\")\n (\"list\", boost::program_options::value (), \"specify a list of motifs\")\n (\"motif\", boost::program_options::value(), \"specify one motif file\")\n (\"kmer,k\", boost::program_options::value(&kmer_length)->default_value(8), \"specify the kmer length\")\n (\"gap,g\", boost::program_options::value(&gap_length)->default_value(0), \"specify the gap length\")\n (\"kmerflag,f\", boost::program_options::bool_switch(&kmerflag), \"flag to switch to the kmer counting-score procedure\")\n (\"revcomp,r\",boost::program_options::bool_switch(&revcomflag),\"reverse compliment sequence\")\n (\"output,o\",boost::program_options::bool_switch(&outflag),\"output the kmer count-score\")\n (\"corr,c\",boost::program_options::bool_switch(&corrflag),\"output the correlation score (un centered cosine)\")\n ;\n boost::program_options::variables_map vm;\n boost::program_options::positional_options_description p;\n p.add(\"fasta\",-1);\n boost::program_options::store(boost::program_options::command_line_parser(argc,argv).options(desc).positional(p).run(), vm);\n boost::program_options::notify(vm);\n \n if (vm.count(\"list\"))\n {\n const char* temx=vm[\"list\"].as().c_str();\n motif_counts= listParser(temx,names_motif, motif_len, matrixmap, pseudo_count);\n }\n if (vm.count(\"motif\")) {\n const char* temname =vm[\"motif\"].as().c_str();\n motif_counts=1;\n strcpy(list_name,temname);\n names_motif[0]=(std::string) list_name;\n Matrixfile(temname, matrixmap, pseudo_count);\n }\n if (vm.count(\"fasta\"))\n {\n const char * fastaname=vm[\"fasta\"].as().c_str();\n motif_len[0]=matrixmap[0].at(\"A\").size();\n strcpy(fasta_name, fastaname );\n }\n if (vm.count(\"help\")) {\n std::cout << \"Usage:\" << argv[0] << \" [options]\\n\";\n std::cout << desc;\n return 0;\n }\n\n \n\n// Load fasta sequence one by one;\n gzFile fp;\n kseq_t *seq;\n int l;\n fp=gzopen(fasta_name, \"r\");\n seq=kseq_init(fp);\n while((l=kseq_read(seq)) >=0){\n std::string seqnametmp, seqtmp;\n seqnametmp= &seq->name.s[0];\n seqtmp= &seq->seq.s[0];\n if(revcomflag)\n seqtmp=seq_revcomp(seqtmp);\n \n for(int i=0;i < motif_counts ; i++){\n if(kmerflag)\n kmerizing(&seqnametmp, &seqtmp,kmer_length,gap_length,&names_motif[i], &matrixmap[i]);\n else\n GenomeMap(&seqnametmp, &seqtmp,motif_len[i],&names_motif[i], &matrixmap[i]);\n }\n }\n kseq_destroy(seq);\n gzclose(fp);\n if(kmerflag && outflag)\n hashOut();\n if(kmerflag && corrflag)\n unCenterCorr();\n\n return 0;\n}\n\n//output the kmer count-score table\nvoid hashOut(){\n for(auto it=kstore.begin(); it !=kstore.end(); it++)\n std::cout<first << \"\\t\" << it->second.count<< \"\\t\" << it->second.discore <first << \"\\t\" << it->second.count<< \"\\t\" << it->second.discore << \"\\t\" << it->second.monoscore <second.count * it->second.count;\n sumy+=it->second.discore * it->second.discore ;\n sumz+=it->second.monoscore * it->second.monoscore ;\n sumxy+= it->second.count * it->second.discore;\n sumxz+= it->second.count * it->second.monoscore;\n }\n// std::cout << sumxy/sqrt(sumx *sumy)<< \"\\t\" << sumxz/sqrt(sumx *sumz) << std::endl;\n std::cout << sumxy/sqrt(sumx *sumy)<< std::endl;\n}\n\n// function to score all the locus in the sequence\nvoid GenomeMap(std::string *id, std::string *seq, long monoLen, std::string *mname, std::unordered_map >* map ){\n unsigned long slen =seq->size();\n \n std::transform(seq->begin(), seq->end(), seq->begin(),::toupper);\n std::replace(seq->begin(),seq->end(),'T','U');\n \n for(long i=0; i < slen - monoLen +1 ; i++){\n std::string subseq=seq->substr(i,monoLen);\n if(subseq.find(\"N\") != std::string::npos)\n continue;\n double mscore=0,dscore=0,rc_mscore=0,rc_dscore=0;\n std::string rc_subseq=seq_revcomp(subseq);\n \n mscore=singleStringScore(mscore, &subseq, 0, map);\n dscore= pairStringScore(dscore, &subseq,0, map);\n rc_mscore=singleStringScore(rc_mscore, &rc_subseq, 0,map);\n rc_dscore=pairStringScore(rc_dscore,&rc_subseq,0,map);\n std::cout << *id << \"\\t\"<< i << \"\\t\" << std::setprecision(5) < >* map,double pcount){\n std::fstream motif_list;\n char motif_file_name[100];\n motif_list.open(list_name);\n int motif_line=0;\n \n while( motif_list.getline( motif_file_name,100) ){\n Matrixfile(motif_file_name, &map[motif_line], pcount);\n// std::cout << motif_file_name << std::endl;\n length[motif_line]=(int) (map[motif_line])[\"A\"].size();\n names[motif_line]=(std::string) motif_file_name;\n ++motif_line;\n }\n// std::cout << motif_line << \" motifs loaded \\n\"< > *y, double pseudo_count){\n std::fstream file;\n file.open(x);\n \n while(!file.is_open()){\n std::cout << \"Something wrong with the filename\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n int line_count=0;\n std::string iss;\n while(getline(file, iss)){\n line_count++;\n if(line_count <=2){\n continue;\n }\n else if(line_count >=3 and line_count <=18){\n fetch_matrix(y, iss, 1, pseudo_count);\n }\n else if(line_count >=19 && line_count<=22){\n fetch_matrix(y, iss, 2, pseudo_count);\n }\n }\n}\n\n//show the matrix and output or the screen\nvoid show_matrix(std::unordered_map > *x){\n for(auto it=(*x).begin(); it !=(*x).end(); it++){\n std::cout << it->first << \"\\t\";\n std::vector tem= it->second;\n for( int i=0; i< tem.size(); ++i)\n std::cout << \"\\t\" << tem[i];\n std::cout << std::endl;\n }\n}\nstd::string seq_revcomp(std::string str){\n std::string rc_seq;\n for(int i=str.size()-1; i>=0; --i){\n rc_seq += (char) basemap[(int)str[i]];\n }\n return rc_seq;\n}\n\n//store the matrix into map table\nvoid fetch_matrix(std::unordered_map > *map, std::string str, int ind, double count){\n std::vector matrix;\n std::stringstream ms(str);\n std::string units;\n while(ms >> units){\n matrix.push_back(units);\n }\n unsigned long matrix_length_raw=matrix.size();\n std::string base_name= matrix.back();\n long matrix_length_new;\n if(ind ==1){\n base_name=base_name.substr(0,2);\n matrix_length_new=matrix_length_raw-2;\n }\n else if(ind==2){\n base_name=base_name.substr(14,1);\n matrix_length_new=matrix_length_raw-1;\n }\n double new_matrix[matrix_length_new];\n std::vector hallo (new_matrix,new_matrix+ matrix_length_new);\n for(int i=0; i< matrix_length_new; i++){\n std::string::size_type sz;\n hallo[i]= std::stod(matrix[i], &sz);\n if(ind ==1)\n hallo[i] = std::log2((hallo[i]+ count)/(0.0625 + count));\n else\n hallo[i] = std::log2((hallo[i]+ count)/(0.25+ count));\n }\n map->insert({base_name,hallo});\n// return map;\n}\n\n//function to generate the kmer count-score table\nvoid kmerizing (std::string* id, std::string* seq, int kmer, int gap, std::string* name, std::unordered_map > *map){\n std::transform(seq->begin(), seq->end(), seq->begin(),::toupper);\n std::replace(seq->begin(),seq->end(),'T','U');\n unsigned long seq_length=seq->size();\n int raw_kseq_len=kmer+gap;\n\n for(unsigned long i=0; i < seq_length-raw_kseq_len +1; i++){\n std::string subseq=seq->substr(i,raw_kseq_len);\n if(subseq.find(\"N\") != std::string::npos)\n continue;\n \n if(gap >0){\n for (int ii=1; ii > *map, int gap_len, int gap_pos){\n long monoLen=(*map)[\"A\"].size();\n if(gap_len >0)\n subseq.replace(gap_pos,gap_len, gap_len, '-' );\n \n long kseq_prime_len= subseq.size();\n long cycle=kseq_prime_len+ monoLen;\n std::string valid_seq;\n double maximum_score=-1000;\n for(int p=0; p < cycle -1 ; p++){\n long pos;\n double score=0;\n if(p = kseq_prime_len){\n valid_seq=subseq.substr(kseq_prime_len-(p+1),p+1);\n pos=0;\n }\n else if(monoLen < kseq_prime_len){\n pos=0;\n if(p =kseq_prime_len -1){\n if(monoLen >=kseq_prime_len){\n pos=p+1-kseq_prime_len;\n if(p maximum_score)?score:maximum_score;\n }\n return maximum_score ;\n}\n// The scoring function for the dependency matrix\ndouble discoring(std::string subseq, std::unordered_map > *map, int gap_len, int gap_pos){\n if(gap_len >0)\n subseq.replace(gap_pos,gap_len,gap_len,'-');\n long monoLen=(*map)[\"A\"].size();\n long kseq_prime_len=subseq.size();\n double maximum_score=-1000;\n if(monoLen %2 ==0){ //matrix length is even\n for(int p=0; p < monoLen + kseq_prime_len -1; p++){\n std::string subs;\n double score=0;\n long pos;\n if( p< monoLen/2){\n if( p < kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-1-p,p+1); //for kmers longer than the 1/2 matrix length\n pos=0;\n }\n else if(p >=kseq_prime_len-1){ //for kmers shorter than the 1/2 marix length\n subs=subseq;\n pos=p-kseq_prime_len+1;\n }\n score= singleStringScore(score, &subs, pos, map);\n maximum_score=(score > maximum_score)?score:maximum_score;\n }\n else if(p >= monoLen/2 && (p - monoLen/2 < kseq_prime_len -1)){\n std::string left_seq; // leftover from the kmer which has been cut for dinucleotide matrix\n long single_pos;\n if(kseq_prime_len <= monoLen && kseq_prime_len >= 0.5 * monoLen){\n if(2*(p-(monoLen/2 -1)) <=kseq_prime_len){\n subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n single_pos=p+1-subs.size();\n if(p+1 >= kseq_prime_len){\n pos=p+1-kseq_prime_len;\n left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen/2-1))); //if($kseq_prime_len-2*($p-($mono_len/2 -1)) > 0);\n }\n else{\n pos=0;\n left_seq=subseq.substr(kseq_prime_len-(p+1),p+1-2*(p-(monoLen/2-1)));\n }\n }\n else{\n subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 )+1) );\n pos=p-kseq_prime_len+1+subs.size();\n single_pos=p+1-kseq_prime_len;\n if(p >= monoLen ){\n std::string left_seq_pre=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2-1))));\n left_seq=left_seq_pre.substr(0,kseq_prime_len-(p+1-monoLen)-subs.size());\n }\n else\n left_seq=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n }\n// std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n }\n else if(kseq_prime_len > monoLen){\n std::string left_seq_pre;\n if(p < monoLen-1){\n subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n if(2*(p-(monoLen/2 -1)) = monoLen-1 && p <= kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-(p+1),monoLen);\n pos=0;\n single_pos=0;\n \n }\n else if(p > kseq_prime_len -1){\n subs=subseq.substr(0,2*(kseq_prime_len-(p-(monoLen/2 -1))));\n left_seq_pre=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n left_seq=left_seq_pre.substr(0, left_seq_pre.size()-(p+1-monoLen));\n pos=p-kseq_prime_len+1+subs.size();\n single_pos=p+1-kseq_prime_len;\n }\n// std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n }\n else if(kseq_prime_len < 0.5 * monoLen){\n if(2*(p-(monoLen/2 -1)) <=kseq_prime_len){\n subs=subseq.substr(kseq_prime_len-2*(p-(monoLen/2 -1)),2*(p-(monoLen/2 -1)));\n pos=p+1-kseq_prime_len;\n left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen/2 -1)));\n single_pos=p+1-subs.size();\n\n }\n else{\n subs=subseq.substr(0,2*(kseq_prime_len-(p-(monoLen/2 -1))));\n pos=p-kseq_prime_len+1+subs.size();\n left_seq=subseq.substr(2*(kseq_prime_len-(p-(monoLen/2 -1))));\n single_pos=p+1-kseq_prime_len;\n }\n }\n\n score=pairStringScore(score,&subs,single_pos,map);\n// std::cout << subseq<< \"\\t\" << subs << \"\\t\" << single_pos << \"\\t\" << pos << std::endl;\n\n if(!left_seq.empty())\n score= singleStringScore(score, &left_seq, pos, map);\n maximum_score=(score > maximum_score)?score:maximum_score;\n }\n else if(p >= monoLen/2 + kseq_prime_len -1){\n if(p = monoLen){\n subs=subseq.substr(0,kseq_prime_len-(p-monoLen)-1);\n pos=p+1-kseq_prime_len;\n }\n score= singleStringScore(score, &subs, pos, map);\n maximum_score=(score > maximum_score)?score:maximum_score;\n }\n }\n }\n else{\n for(int p=0; p < monoLen + kseq_prime_len -1; p++){\n std::string subs;\n double score=0;\n long pos;\n if( p < (monoLen-1)/2){\n if(p < kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-1-p,p+1); // for kmers longer than the 1/2 matrix length\n pos=0;\n }\n else if(p >=kseq_prime_len-1){ //for kmers shorter than the 1/2marix length\n subs=subseq;\n pos=p-kseq_prime_len+1;\n }\n score= singleStringScore(score, &subs, pos, map);\n maximum_score=(score > maximum_score)?score:maximum_score;\n }\n else if(p >= (monoLen-1)/2 && (p - (monoLen-1)/2 <= kseq_prime_len -1)){\n std::string left_seq;\n long single_pos;\n if(kseq_prime_len <= monoLen && kseq_prime_len >= 0.5 * (monoLen-1)){\n if(2*(p-(monoLen-1)/2 ) <=kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)-1);\n single_pos=p+1-subs.size();\n pos=0;\n if(p+1 >= kseq_prime_len){\n pos=p+1-kseq_prime_len;\n left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen-1)/2)-1); //if($kseq_prime_len-2*($ p-($mono_len/2 -1)) > 0);\n }\n else{\n pos=0;\n left_seq=subseq.substr(kseq_prime_len-(p+1),p+1-2*(p-(monoLen-1)/2)-1);\n }\n }\n else{\n subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n pos= p-kseq_prime_len+1+subs.size();\n single_pos=p+1-kseq_prime_len;\n if(p >= monoLen){\n std::string left_seq_pre=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n left_seq=left_seq_pre.substr(0,kseq_prime_len-(p+1-monoLen)-subs.size());\n }\n else{\n left_seq=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n }\n }\n }\n else if( kseq_prime_len > monoLen){\n std::string left_seq_pre;\n if(p < monoLen-1){\n subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)+1);\n if(2*(p-(monoLen/2 -1)) < kseq_prime_len)\n left_seq_pre=subseq.substr(0,kseq_prime_len-2*(p+1-(monoLen-1)/2)+1);\n left_seq=left_seq_pre.substr(kseq_prime_len - (p+1));\n pos=0;\n single_pos=p+1-subs.size();\n }\n else if( p >= monoLen-1 && p <= kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-(p+1),monoLen);\n pos=0;\n single_pos=0;\n }\n else if(p > kseq_prime_len -1){\n subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n left_seq_pre=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2 ))+1);\n left_seq=left_seq_pre.substr(0, left_seq_pre.size()-(p+1-monoLen));\n pos=p-kseq_prime_len+1+subs.size();\n single_pos=p+1-kseq_prime_len;\n }\n }\n else if(kseq_prime_len < 0.5 * (monoLen-1)){\n if(2*(p-(monoLen-1)/2 ) <=kseq_prime_len-1){\n subs=subseq.substr(kseq_prime_len-2*(p+1-(monoLen-1)/2)+1,2*(p+1-(monoLen-1)/2)+1);\n pos=p+1-kseq_prime_len;\n left_seq=subseq.substr(0,kseq_prime_len-2*(p-(monoLen-1)/2)-1);\n single_pos=p+1-subs.size();\n }\n else{\n subs=subseq.substr(0,2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n pos= p-kseq_prime_len+1+ subs.size();\n left_seq=subseq.substr(2*(kseq_prime_len-(p+1-(monoLen-1)/2))+1);\n single_pos=p+1-kseq_prime_len;\n }\n }\n score=pairStringScore(score,&subs,single_pos,map);\n if(!left_seq.empty())\n score= singleStringScore(score, &left_seq, pos, map);\n maximum_score=(score > maximum_score)?score:maximum_score;\n }\n else if(p >= (monoLen-1)/2 +kseq_prime_len -1){\n if(p = monoLen){\n subs=subseq.substr(0,kseq_prime_len-(p-monoLen)-1);\n pos=p+1-kseq_prime_len;\n }\n score= singleStringScore(score, &subs, pos, map);\n maximum_score=(score > maximum_score )?score:maximum_score;\n }\n }\n }\n return maximum_score;\n}\n//sub-routines for the dangling sequence\ninline double singleStringScore(double x, std::string* s, long p, std::unordered_map > *m){\n for(int j=0; jsize(); j++){\n std::string letter=s->substr(j,1);\n if(letter == \"-\")\n continue;\n x+= (*m)[letter][p+j];\n }\n return x;\n}\n//sub-routines for the paired sequence\ninline double pairStringScore(double x, std::string * s, long sp, std::unordered_map > *m){\n long subs_len=s->size();\n long diLen=(*m)[\"AA\"].size();\n int half_subs_len;\n if(subs_len %2==0)\n half_subs_len=0.5* subs_len ;\n else\n half_subs_len=0.5* (subs_len-1) ;\n \n for (int j=0; j <= half_subs_len -1 ; j++){\n std::string letterA=s->substr(j,1);\n std::string letterB=s->substr(subs_len-j-1,1);\n std::string letter;\n\n if(letterA ==\"-\" && letterB==\"-\")\n continue;\n else if(letterA ==\"-\" ||letterB==\"-\"){\n long spos;\n if(letterB==\"-\"){\n spos=sp +j ;\n letter=letterA;\n }//#letterA is not gap so use the postion from the subs' beginning\n else if(letterA==\"-\"){\n spos=sp+(subs_len-1)-j; //#B is not gap, so from the end of subs\n letter=letterB;\n }\n x+=(*m)[letter][spos];\n }\n else{\n letter=letterA+letterB;\n// std::cout << *s << \"\\t\" << letter << \"\\t\" << diLen-half_subs_len+j<< std::endl;\n x+=(*m)[letter][diLen-half_subs_len+j];\n }\n }\n return x;\n}\n\n\n\n", "meta": {"hexsha": "f6c00cf8b848a561d8ada4ce1375ca87d7befdb3", "size": 30345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zhjilin/rmap", "max_stars_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T06:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T22:14:40.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "zhjilin/rmap", "max_issues_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_issues_repo_licenses": ["MIT"], "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": "zhjilin/rmap", "max_forks_repo_head_hexsha": "44dd7e336303181c53733a3fa30cdd274c08fa5d", "max_forks_repo_licenses": ["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.1036931818, "max_line_length": 184, "alphanum_fraction": 0.5074971165, "num_tokens": 8549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19954526699110245}} {"text": "/*\n\nCopyright (c) 2005-2021, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 * Neither the name of the University of Oxford nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n\n#ifndef EXTENDEDBIDOMAINTISSUE_HPP_\n#define EXTENDEDBIDOMAINTISSUE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include \n\n#include \n#include \"UblasMatrixInclude.hpp\"\n\n#include \"AbstractStimulusFunction.hpp\"\n#include \"AbstractStimulusFactory.hpp\"\n#include \"AbstractConductivityTensors.hpp\"\n\n#include \"AbstractCardiacTissue.hpp\"\n\n/**\n * Class that provides functionalities to specify a tissue within the context of the extended bidomain framework.\n *\n * The extended bidomain equations are of the form:\n *\n * - div ( sigma_i1 grad Phi_1 ) + Am1*Cm1*d(phi_1)/dt - Am2*Cm2*d(phi_e)/dt + Am1*I_ion1 - Am1*I_stim1 + Amgap*G_gap*(phi_1 - phi_2)\n * - div ( sigma_i2 grad Phi_2 ) + Am2*Cm2*d(phi_2)/dt - Am2*Cm2*d(phi_e)/dt + Am2*I_ion2 - Am2*I_stim2 - Amgap*G_gap*(phi_1 - phi_2)\n * div ( sigma_e grad Phi_e ) + div ( sigma_i1 grad Phi_1 ) + div ( sigma_i2 grad Phi_2 ) = I_stim\n *\n * The unknowns are:\n *\n * - Phi_1 (intracellular potential of the first cell).\n * - Phi_2 (intracellular potential of the second cell).\n * - Phi_e (extracellular potential).\n *\n * Am1, Am2 and Amgap are surface-to-volume ratios for first cell, second cell and gap junction. User can set their values.\n * Cm1 and cm2 are capaciatnce values of first and second cell respectively\n * sigma_i1 and sigma_i2 are intracellular conductivity tensors of first and second cell respectively\n * sigma_e is the conductivity tensor for the extracellular space\n * G_gap is the conductance (in ms/cm2) of the gap junction channel.\n *\n *\n *\n */\ntemplate \nclass ExtendedBidomainTissue : public virtual AbstractCardiacTissue\n{\nprivate:\n friend class TestExtendedBidomainTissue; // for testing.\n\n /** Needed for serialization. */\n friend class boost::serialization::access;\n /**\n * Archive the member variables.\n *\n * @param archive\n * @param version\n */\n template\n void serialize(Archive & archive, const unsigned int version)\n {\n archive & boost::serialization::base_object >(*this);\n // Conductivity tensors are dealt with by HeartConfig, and the caches get regenerated.\n\n archive & mAmFirstCell;\n archive & mAmSecondCell;\n archive & mAmGap;\n archive & mCmFirstCell;\n archive & mCmSecondCell;\n archive & mGGap;\n archive & mUserSuppliedExtracellularStimulus;\n }\n\n /** Intracellular conductivity tensors for the second cell.*/\n AbstractConductivityTensors *mpIntracellularConductivityTensorsSecondCell;\n\n /**\n * Stores the values of the conductivities for the second cell. Accessible via get and set methods. The problem class will set it\n * This variable is a convenient interface for other classes. It is used to fill in mpIntracellularConductivityTensorsSecondCell.\n */\n c_vector mIntracellularConductivitiesSecondCell;\n\n\n /** Extracellular conductivity tensors. */\n AbstractConductivityTensors *mpExtracellularConductivityTensors;\n\n /**\n * Cache containing all the stimulus currents for each node,\n * replicated over all processes.\n */\n ReplicatableVector mExtracellularStimulusCacheReplicated;\n\n /**\n * Cache containing all the stimulus currents for each node,\n * replicated over all processes.\n */\n ReplicatableVector mGgapCacheReplicated;\n\n /**\n * Cache containing all the ionic currents for each node for the seconed cell,\n * replicated over all processes.\n */\n ReplicatableVector mIionicCacheReplicatedSecondCell;\n\n /**\n * Cache containing all the stimulus currents for each node for the second cell,\n * replicated over all processes.\n */\n ReplicatableVector mIntracellularStimulusCacheReplicatedSecondCell;\n\n /** The vector of cells (the second one). Distributed. */\n std::vector< AbstractCardiacCellInterface* > mCellsDistributedSecondCell;\n\n /** The vector of stimuli for the extracellular stimulus. Distributed. */\n std::vector > mExtracellularStimuliDistributed;\n\n /** The vector of gap junction conductances. Distributed*/\n std::vector mGgapDistributed;\n\n /**the Am for the first cell, set by the problem class and picked up by the assembler*/\n double mAmFirstCell;\n /**the Am for the second cell, set by the problem class and picked up by the assembler*/\n double mAmSecondCell;\n /**the Am for the gap junction, set by the problem class and picked up by the assembler*/\n double mAmGap;\n /**the Cm for the first cell, set by the problem class and picked up by the assembler*/\n double mCmFirstCell;\n /**the Cm for the second cell, set by the problem class and picked up by the assembler*/\n double mCmSecondCell;\n /**the conductance of the gap junction, in mS/cm2. Set by the problem class and picked up by the assembler*/\n double mGGap;\n\n /**\n * Whether the extracellular stimulus that is passed in was supplied by the user or not\n * (it could be the default zero implementation). Initialise to false (user did not pass in anything).\n */\n bool mUserSuppliedExtracellularStimulus;\n\n /**\n * Convenience method for extracellular conductivity tensors creation\n */\n void CreateExtracellularConductivityTensors();\n\n /**\n * The parent class AbstractCardiacTissue has a method UpdateCaches that updates some caches of general use.\n * This method updates more caches that are specific to extended bidomain problems, namely:\n *\n * - Iionic and intracellular stimulus for the second cell\n * - Extracellular stimulus\n * - Gap junction conductivities (Ggap)\n *\n * It is typically called right after the UpdateCaches method in the parent class.\n *\n * @param globalIndex global index of the entry to update\n * @param localIndex local index of the entry to update\n * @param nextTime the next PDE time point, at which to evaluate the stimulus current\n */\n void UpdateAdditionalCaches(unsigned globalIndex, unsigned localIndex, double nextTime);\n\n /**\n * The parent class AbstractCardiacTissue has a method ReplicateCaches that replicates some caches of general use.\n * This method replicates more caches that are specific to extended bidomain problems, namely:\n *\n * - Iionic and intracellular stimulus for the second cell\n * - Extracellular stimulus\n * - Gap junction conductivities (Ggap)\n *\n * It is typically called right after the ReplicateCaches method in the parent class.\n */\n void ReplicateAdditionalCaches();\n\n /** vector of regions for Ggap heterogeneities*/\n std::vector > > mGgapHeterogeneityRegions;\n /**values of heterogeneous Ggaps corresponding to mGgapHeterogeneityRegions. This has the same size as mGgapHeterogeneityRegions*/\n std::vector mGgapValues;\n\npublic:\n\n /**\n * Constructor sets up extracellular conductivity tensors.\n * @param pCellFactory factory to pass on to the base class constructor\n * @param pCellFactorySecondCell factory to pass on to the base class constructor for the second cell\n * @param pExtracellularStimulusFactory factory for creating extracellular stimuli\n */\n ExtendedBidomainTissue(AbstractCardiacCellFactory* pCellFactory, AbstractCardiacCellFactory* pCellFactorySecondCell, AbstractStimulusFactory* pExtracellularStimulusFactory);\n\n /**\n * Archiving constructor\n * @param rCellsDistributed local cell models (recovered from archive)\n * @param rSecondCellsDistributed local cell models for second cells (recovered from archive)\n * @param rExtraStimuliDistributed local extracellular stimuli (recovered from archive)\n * @param rGgapsDistributed distributed Ggaps (recovered from archive)\n * @param pMesh a pointer to the AbstractTetrahedral mesh (recovered from archive).\n * @param intracellularConductivitiesSecondCell a vector with the orthotropic conductivities for the second cell (this is needed because the second cell values may not be taken from HeartConfig as the the ones for the first cell are).\n */\n ExtendedBidomainTissue(std::vector & rCellsDistributed,\n std::vector & rSecondCellsDistributed,\n std::vector > & rExtraStimuliDistributed,\n std::vector& rGgapsDistributed,\n AbstractTetrahedralMesh* pMesh,\n c_vector intracellularConductivitiesSecondCell);\n\n /**\n * Destructor\n */\n virtual ~ExtendedBidomainTissue();\n\n /**\n * Sets the value of the conductivities for the second cell.\n *\n * @param conductivities the conductivities to be set.\n */\n void SetIntracellularConductivitiesSecondCell(c_vector conductivities);\n\n /**\n * @return a pointer to the second cell\n *\n * @param globalIndex the global index in the mesh\n */\n AbstractCardiacCellInterface* GetCardiacSecondCell( unsigned globalIndex );\n\n\n /**\n * @return a pointer to the extracellular stimulus. Useful for testing\n *\n * @param globalIndex the global index in the mesh\n */\n boost::shared_ptr GetExtracellularStimulus( unsigned globalIndex );\n\n /**\n * @return a reference to the vector of distributed cells (second cell). Needed for archiving.\n */\n const std::vector& rGetSecondCellsDistributed() const;\n\n /**\n * @return a reference to the vector of distributed values of Ggaps. Needed for archiving.\n */\n const std::vector& rGetGapsDistributed() const;\n\n\n /**\n * @return a reference to the vector of distributed extracellular stimuli. Needed for archiving.\n */\n const std::vector >& rGetExtracellularStimulusDistributed() const;\n\n\n /**\n * @return the intracellular conductivities of the second cell\n */\n c_vector GetIntracellularConductivitiesSecondCell() const;\n\n /**\n * Integrate the cell ODEs and update ionic current etc for each of the\n * cells, between the two times provided. This is a re-implementation from the version in the base class.\n *\n * @param existingSolution the current voltage solution vector\n * @param time the current simulation time\n * @param nextTime when to simulate the cells until\n * @param updateVoltage (unused here)\n */\n virtual void SolveCellSystems(Vec existingSolution, double time, double nextTime, bool updateVoltage = false);\n\n /**\n * Convenience method for intracellular conductivity tensors creation for the second cell\n */\n void CreateIntracellularConductivityTensorSecondCell();\n\n /**\n * Set the values of mCellHeterogeneityRegions and mGgapValues for the heterogeneities of Ggap.\n *\n * @param rGgapHeterogeneityRegions a vector of (pointers to) heterogeneity regions for gap junctions\n * @param rGgapValues a vector (of the same size as rGgapHeterogeneityRegions) with the respective values of Ggap for every region.\n */\n void SetGgapHeterogeneities ( std::vector > > & rGgapHeterogeneityRegions, std::vector rGgapValues);\n\n /**\n * Create the pattern of Ggap across the mesh based upon mCellHeterogeneityRegions, mGgapValues and mGgap. This will fill in mGgapDistributed.\n * It will set mGgap everywhere except in the areas mCellHeterogeneityRegions[i] where it will put mGgapValues[i] instead.\n * If mCellHeterogeneityRegions (and mGgapValues) are empty, mGgap will be set everywhere.\n */\n void CreateGGapConductivities();\n\n /**\n * @return the extracellular conductivity tensor for the given element\n * @param elementIndex index of the element of interest\n */\n const c_matrix& rGetExtracellularConductivityTensor(unsigned elementIndex);\n\n /**\n * @return the intracellular conductivity tensor for the given element for tehs econd cell\n * @param elementIndex index of the element of interest\n */\n const c_matrix& rGetIntracellularConductivityTensorSecondCell(unsigned elementIndex);\n\n\n /** @return the entire ionic current cache for the second cell*/\n ReplicatableVector& rGetIionicCacheReplicatedSecondCell();\n\n /** @return the entire stimulus current cache for the second cell*/\n ReplicatableVector& rGetIntracellularStimulusCacheReplicatedSecondCell();\n\n /** @return the extracellular stimulus*/\n ReplicatableVector& rGetExtracellularStimulusCacheReplicated();\n\n /** @return the values of ggap*/\n ReplicatableVector& rGetGgapCacheReplicated();\n\n /**\n * @return Am for the first cell\n */\n double GetAmFirstCell();\n\n /**\n * @return Am for the second cell\n */\n double GetAmSecondCell();\n\n /**\n * @return Am for the gap junction\n */\n double GetAmGap();\n\n /**\n * @return Cm for the first cell\n */\n double GetCmFirstCell();\n\n /**\n * @return Cm for the second cell\n */\n double GetCmSecondCell();\n\n /**\n * @return the conducatnce of the gap junction (mGGap)\n */\n double GetGGap();\n\n /**\n * @param value Am for the first cell\n */\n void SetAmFirstCell(double value);\n\n /**\n * @param value Am for the second cell\n */\n void SetAmSecondCell(double value);\n\n /**\n * @param value Am for the gap junction\n */\n void SetAmGap(double value);\n\n /**\n * @param value Cm for the first cell\n */\n void SetCmFirstCell(double value);\n\n /**\n * @param value Cm for the first cell\n */\n void SetCmSecondCell(double value);\n\n /**\n * @param value conductance, in mS of the gap junction\n */\n void SetGGap(double value);\n\n /**\n * This method gives access to the member variable mUserSuppliedExtracellularStimulus,\n * which is false by default but turned true if the user supplies an extracellular stimulus\n * in any form.\n *\n * @return true if the user supplied an extracellular stimulus.\n */\n bool HasTheUserSuppliedExtracellularStimulus();\n\n /**\n * This method allows modifications of the mUserSuppliedExtracellularStimulus flag (false by default).\n * Other classes (e.g., Problem classes) can use this method to tell the Tissue that the user\n * specified an extracellular stimulus.\n *\n * @param flag ; true if you want to tell the Tissue object that the user supplied an extracellular stimulus explicitly\n */\n void SetUserSuppliedExtracellularStimulus(bool flag);\n\n\n /**\n * This method is the equivalent of SaveCardiacCells in the abstract class but save both cells of the extended bidomain tissue\n *\n * @param archive the master archive; cells will actually be written to the process-specific archive.\n * @param version\n */\n template\n void SaveExtendedBidomainCells(Archive & archive, const unsigned int version) const\n {\n Archive& r_archive = *ProcessSpecificArchive::Get();\n const std::vector & r_cells_distributed = this->rGetCellsDistributed();\n const std::vector & r_cells_distributed_second_cell = rGetSecondCellsDistributed();\n const std::vector & r_ggaps_distributed = rGetGapsDistributed();\n\n r_archive & this->mpDistributedVectorFactory; // Needed when loading\n const unsigned num_cells = r_cells_distributed.size();\n r_archive & num_cells;\n for (unsigned i=0; i(r_cells_distributed[i]);\n bool is_dynamic = (p_entity != NULL);\n r_archive & is_dynamic;\n if (is_dynamic)\n {\n #ifdef CHASTE_CAN_CHECKPOINT_DLLS\n ///\\todo Dynamically loaded cell models aren't saved to archive in extended Bidomain\n NEVER_REACHED;\n //r_archive & p_entity->GetLoader()->GetLoadableModulePath();\n #else\n // We should have thrown an exception before this point\n NEVER_REACHED;\n #endif // CHASTE_CAN_CHECKPOINT_DLLS\n }\n r_archive & r_cells_distributed[i];\n r_archive & r_cells_distributed_second_cell[i];\n r_archive & r_ggaps_distributed[i];\n }\n }\n\n /**\n * Load our tissue from an archive. This is the equivalent of LoadCardiacCells in the abstract class.\n * it loads the two cells instead of only one.\n *\n * Handles the checkpoint migration case, deleting loaded cells immediately if they are\n * not local to this process.\n *\n * @param archive the process-specific archive to load from\n * @param version archive version\n * @param rCells vector to fill in with pointers to local cells\n * @param rSecondCells vector to fill in with pointers to the second cells\n * @param rGgaps vector of values of gap junctions\n * @param pMesh the mesh, so we can get at the node permutation, if any\n */\n template\n static void LoadExtendedBidomainCells(Archive & archive, const unsigned int version,\n std::vector& rCells,\n std::vector& rSecondCells,\n std::vector& rGgaps,\n AbstractTetrahedralMesh* pMesh)\n {\n assert(pMesh!=NULL);\n DistributedVectorFactory* p_factory;\n archive & p_factory;\n unsigned num_cells;\n archive & num_cells;\n rCells.resize(p_factory->GetLocalOwnership());\n rSecondCells.resize(p_factory->GetLocalOwnership());\n rGgaps.resize(p_factory->GetLocalOwnership());\n #ifndef NDEBUG\n // Paranoia\n assert(rCells.size() == rSecondCells.size());\n for (unsigned i=0; iGetOriginalFactory() ? p_factory->GetOriginalFactory()->GetLow() : p_factory->GetLow();\n\n for (unsigned local_index=0; local_indexGetLow();\n bool local = p_factory->IsGlobalIndexLocal(global_index);\n\n bool is_dynamic;\n archive & is_dynamic;\n\n if (is_dynamic)\n {\n #ifdef CHASTE_CAN_CHECKPOINT_DLLS\n ///\\todo Dynamically loaded cell models aren't loaded from archive in extended Bidomain\n NEVER_REACHED;\n // Ensure the shared object file for this cell model is loaded.\n // We need to do this here, rather than in the class' serialization code,\n // because that code won't be available until this is done...\n// std::string shared_object_path;\n// archive & shared_object_path;\n// DynamicModelLoaderRegistry::Instance()->GetLoader(shared_object_path);\n #else\n // Could only happen on Mac OS X, and will probably be trapped earlier.\n NEVER_REACHED;\n #endif // CHASTE_CAN_CHECKPOINT_DLLS\n }\n\n AbstractCardiacCellInterface* p_cell;\n AbstractCardiacCellInterface* p_second_cell;\n double g_gap;\n archive & p_cell;\n archive & p_second_cell;\n archive & g_gap;\n if (local)\n {\n rCells[new_local_index] = p_cell; // Add to local cells\n rSecondCells[new_local_index] = p_second_cell;\n rGgaps[new_local_index] = g_gap;\n }\n else\n {\n //not sure how to cover this, we are already looping over local cells...\n NEVER_REACHED;\n // Non-local real cell, so free the memory.\n // delete p_cell;\n // delete p_second_cell;\n }\n }\n }\n\n /**\n * This method is the equivalent of SaveCardiacCells but Saves the extracellular stimulus instead\n *\n * @param archive the master archive; cells will actually be written to the process-specific archive.\n * @param version\n */\n template\n void SaveExtracellularStimulus(Archive & archive, const unsigned int version) const\n {\n Archive& r_archive = *ProcessSpecificArchive::Get();\n const std::vector > & r_stimulus_distributed = rGetExtracellularStimulusDistributed();\n r_archive & this->mpDistributedVectorFactory; // Needed when loading\n const unsigned num_cells = r_stimulus_distributed.size();\n r_archive & num_cells;\n for (unsigned i=0; i\n void LoadExtracellularStimulus(Archive & archive, const unsigned int version,\n std::vector >& rStimuli,\n AbstractTetrahedralMesh* pMesh)\n {\n\n DistributedVectorFactory* p_factory;\n archive & p_factory;\n unsigned num_cells;\n archive & num_cells;\n rStimuli.resize(p_factory->GetLocalOwnership());\n#ifndef NDEBUG\n // Paranoia\n for (unsigned i=0; iGetOriginalFactory() ? p_factory->GetOriginalFactory()->GetLow() : p_factory->GetLow();\n\n assert(pMesh!=NULL);\n //unsigned num_cells = pMesh->GetNumNodes();\n for (unsigned local_index=0; local_indexGetLow();\n bool local = p_factory->IsGlobalIndexLocal(global_index);\n\n boost::shared_ptr p_stim;\n archive & p_stim;//get from archive\n\n if (local)\n {\n rStimuli[new_local_index] = p_stim; // Add stimulus to local cells\n }\n //otherwise we should delete, but I think shared pointers delete themselves?\n }\n }\n};\n\n // Declare identifier for the serializer\n #include \"SerializationExportWrapper.hpp\"\n EXPORT_TEMPLATE_CLASS_SAME_DIMS(ExtendedBidomainTissue)\n\n namespace boost\n {\n namespace serialization\n {\n\n template\n inline void save_construct_data(\n Archive & ar, const ExtendedBidomainTissue * t, const unsigned int file_version)\n {\n //archive the conductivity tensor of the second cell (which may not be dealt with by heartconfig)\n c_vector intracellular_conductivities_second_cell = t->GetIntracellularConductivitiesSecondCell();\n //note that simple: ar & intracellular_conductivities_second_cell may not be liked by some boost versions\n for (unsigned i = 0; i < SPACE_DIM; i++)\n {\n ar & intracellular_conductivities_second_cell(i);\n }\n\n const AbstractTetrahedralMesh* p_mesh = t->pGetMesh();\n ar & p_mesh;\n\n // Don't use the std::vector serialization for cardiac cells, so that we can load them\n // more cleverly when migrating checkpoints.\n t->SaveExtendedBidomainCells(ar, file_version);\n t->SaveExtracellularStimulus(ar, file_version);\n\n // Creation of conductivity tensors are called by constructor and uses HeartConfig. So make sure that it is\n // archived too (needs doing before construction so appears here instead of usual archive location).\n HeartConfig* p_config = HeartConfig::Instance();\n ar & *p_config;\n ar & p_config;\n }\n\n /**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate an instance (using existing constructor)\n */\n template\n inline void load_construct_data(\n Archive & ar, ExtendedBidomainTissue * t, const unsigned int file_version)\n {\n //Load conductivities of the conductivity of the second cell.\n c_vector intra_cond_second_cell;\n //note that simple: ar & intra_cond_second_cell may not be liked by some boost versions\n for (unsigned i = 0; i < SPACE_DIM; i++)\n {\n double cond;\n ar & cond;\n intra_cond_second_cell(i) = cond;\n }\n\n\n std::vector cells_distributed;\n std::vector cells_distributed_second_cell;\n std::vector > extra_stim;\n std::vector g_gaps;\n AbstractTetrahedralMesh* p_mesh;\n ar & p_mesh;\n\n // Load only the cells we actually own\n t->LoadExtendedBidomainCells(\n *ProcessSpecificArchive::Get(), file_version, cells_distributed, cells_distributed_second_cell, g_gaps, p_mesh);\n\n t->LoadExtracellularStimulus(\n *ProcessSpecificArchive::Get(), file_version, extra_stim, p_mesh);\n\n // CreateIntracellularConductivityTensor() is called by AbstractCardiacTissue constructor and uses HeartConfig.\n // (as does CreateExtracellularConductivityTensor). So make sure that it is\n // archived too (needs doing before construction so appears here instead of usual archive location).\n HeartConfig* p_config = HeartConfig::Instance();\n ar & *p_config;\n ar & p_config;\n\n ::new(t)ExtendedBidomainTissue(cells_distributed, cells_distributed_second_cell, extra_stim, g_gaps, p_mesh, intra_cond_second_cell);\n }\n }\n } // namespace ...\n\n#endif /*EXTENDEDBIDOMAINTISSUE_HPP_*/\n", "meta": {"hexsha": "c8e0609243796ce52c296fdf002c83bb07e32696", "size": 29619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_stars_repo_name": "mdp19pn/Chaste", "max_stars_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T08:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T11:39:26.000Z", "max_issues_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_issues_repo_name": "mdp19pn/Chaste", "max_issues_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T13:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:42:07.000Z", "max_forks_repo_path": "heart/src/tissue/ExtendedBidomainTissue.hpp", "max_forks_repo_name": "mdp19pn/Chaste", "max_forks_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T13:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:57:35.000Z", "avg_line_length": 41.8939179632, "max_line_length": 238, "alphanum_fraction": 0.6877004625, "num_tokens": 6697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.1995380857505491}} {"text": "/**************************************************************************\\\n *\n * This file is part of the Coin 3D visualization library.\n * Copyright (C) by Kongsberg Oil & Gas Technologies.\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * (\"GPL\") version 2 as published by the Free Software Foundation.\n * See the file LICENSE.GPL at the root directory of this source\n * distribution for additional information about the GNU GPL.\n *\n * For using Coin with software that can not be combined with the GNU\n * GPL, and for taking advantage of the additional benefits of our\n * support services, please contact Kongsberg Oil & Gas Technologies\n * about acquiring a Coin Professional Edition License.\n *\n * See http://www.coin3d.org/ for more information.\n *\n * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.\n * http://www.sim.no/ sales@sim.no coin-support@coin3d.org\n *\n\\**************************************************************************/\n\n#include \n\n#include \n\n#include \n#include \n#include \"engines/SoSubEngineP.h\"\n\n/*!\n \\class SoHeightMapToNormalMap SoHeightMapToNormalMap.h Inventor/engines/SoHeightMapToNormalMap.h\n \\brief Engine for computing a normal map from a height map.\n\n This engine will create a normal map texture from a height map texture.\n You can use it in an Inventor file like this:\n\n \\code\n Texture2 {\n image = HeightMapToNormalMap {\n sourceImage = Texture2 { filename \"HeightMap.jpg\" } . image\n } . image\n }\n \\endcode\n\n Be aware that the field connections will remain active, so both\n Texture2 nodes and the HeightMapToNormalMap engine will be kept resident\n in memory (unless you intervene manually and detach the engine) even\n though only the \"outer\" Texture2 node is needed. This can give quite\n a big memory use overhead.\n\n \\ingroup engines\n \\COIN_CLASS_EXTENSION\n \\since Coin 3.0\n*/\n\n/*!\n \\enum SoHeightMapToNormalMap::NormalMapFormat\n Enumeration of available normal map formats.\n*/\n\n/*!\n \\var SoHeightMapToNormalMap::NormalMapFormat SoHeightMapToNormalMap::INT8\n Encode the normals as a 3 component byte texture.\n This is the only option for now, as long as float textures are not conveniently\n supported in Coin.\n*/\n\n/*!\n \\var SoMFEnum SoHeightMapToNormalMap::format\n This setting decides what kind of normal map is generated. For now, only the\n INT8 format is available, and it is the default value.\n*/\n\nSO_ENGINE_SOURCE(SoHeightMapToNormalMap);\n\n/*!\n Class initializer.\n*/\nvoid\nSoHeightMapToNormalMap::initClass(void)\n{\n SO_ENGINE_INTERNAL_INIT_CLASS(SoHeightMapToNormalMap);\n}\n\n/*!\n Constructor.\n*/\nSoHeightMapToNormalMap::SoHeightMapToNormalMap(void)\n{\n SO_ENGINE_INTERNAL_CONSTRUCTOR(SoHeightMapToNormalMap);\n\n SO_ENGINE_ADD_INPUT(format, (INT8));\n\n SO_ENGINE_DEFINE_ENUM_VALUE(NormalMapFormat, INT8);\n SO_ENGINE_SET_SF_ENUM_TYPE(format, NormalMapFormat);\n}\n\n/*!\n Static function for computing a normal map from a height map.\n This function can be used directly without any engine instantiation.\n*/\nvoid\nSoHeightMapToNormalMap::convert(const unsigned char * srcptr, SbVec2s size, int nc, SbImage & dst_out)\n{\n float dx, dy;\n int width = size[0];\n int height = size[1];\n boost::scoped_array dstarray(new unsigned char[width*height*3]);\n unsigned char * dstptr = dstarray.get();\n unsigned char red;\n SbVec3f n;\n\n#define GET_PIXEL_RED(x_, y_) \\\n srcptr[(y_)*width*nc + (x_)*nc]\n\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n // do Y Sobel filter\n red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n dy = static_cast(red) / 255.0f * -1.0f;\n\n red = GET_PIXEL_RED(x % width, (y+1) % height);\n dy += static_cast(red) / 255.0f * -2.0f;\n\n red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n dy += static_cast(red) / 255.0f * -1.0f;\n\n red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n dy += static_cast(red) / 255.0f * 1.0f;\n\n red = GET_PIXEL_RED(x % width, (y-1+height) % height);\n dy += static_cast(red) / 255.0f * 2.0f;\n\n red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n dy += static_cast(red) / 255.0f * 1.0f;\n\n // Do X Sobel filter\n red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n dx = static_cast(red) / 255.0f * -1.0f;\n\n red = GET_PIXEL_RED((x-1+width) % width, y % height);\n dx += static_cast(red) / 255.0f * -2.0f;\n\n red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n dx += static_cast(red) / 255.0f * -1.0f;\n\n red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n dx += static_cast(red) / 255.0f * 1.0f;\n\n red = GET_PIXEL_RED((x+1) % width, y % height);\n dx += static_cast(red) / 255.0f * 2.0f;\n\n red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n dx += static_cast(red) / 255.0f * 1.0f;\n\n n[0] = -dx;\n n[1] = -dy;\n n[2] = 1.0f;\n (void) n.normalize();\n\n *dstptr++ = static_cast(SbMin((n[0]+1.0f) * 128.0f, 255.0f));\n *dstptr++ = static_cast(SbMin((n[1]+1.0f) * 128.0f, 255.0f));\n *dstptr++ = static_cast(SbMin((n[2]+1.0f) * 128.0f, 255.0f));\n }\n }\n#undef GET_PIXEL_RED\n dst_out.setValue(size, 3, dstarray.get());\n}\n\nvoid\nSoHeightMapToNormalMap::inputChanged(SoField * which)\n{\n // in case we need to override later\n inherited::inputChanged(which);\n}\n\nvoid\nSoHeightMapToNormalMap::evaluate(void)\n{\n SbVec2s size;\n int nc;\n const unsigned char * ptr =\n static_cast(sourceImage.getValue(size, nc));\n\n SbImage targetimg;\n SoHeightMapToNormalMap::convert(ptr, size, nc, targetimg);\n\n ptr = static_cast(targetimg.getValue(size, nc));\n SO_ENGINE_OUTPUT(image, SoSFImage, setValue(size, nc, ptr));\n}\n", "meta": {"hexsha": "886b255d172e83d8498c5ecec13f2b09d3b1d02f", "size": 6093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_stars_repo_name": "KraftOreo/EBM_Hand", "max_stars_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_issues_repo_name": "KraftOreo/EBM_Hand", "max_issues_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grasp_generation/graspitmodified_lm/Coin-3.1.3/src/engines/SoHeightMapToNormalMap.cpp", "max_forks_repo_name": "KraftOreo/EBM_Hand", "max_forks_repo_head_hexsha": "9ab1722c196b7eb99b4c3ecc85cef6e8b1887053", "max_forks_repo_licenses": ["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.5699481865, "max_line_length": 102, "alphanum_fraction": 0.6638765797, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807272299745}} {"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"utility/expect.hpp\"\n#include \"utility/binaryio.hpp\"\n\n#include \"math/math.hpp\"\n#include \"math/geometry.hpp\"\n#include \"math/transform.hpp\"\n\n#include \"imgproc/scanconversion.hpp\"\n\n#include \"half/half.hpp\"\n\n#include \"../storage/error.hpp\"\n\n#include \"mesh.hpp\"\n#include \"meshio.hpp\"\n#include \"multifile.hpp\"\n#include \"math.hpp\"\n#include \"tileindex.hpp\"\n\nnamespace fs = boost::filesystem;\nnamespace bio = boost::iostreams;\nnamespace bin = utility::binaryio;\n\nnamespace half = half_float::detail;\n\nnamespace vtslibs { namespace vts {\n\nnamespace {\n\n/** Geo coordinates to coverage mask mapping.\n * NB: result is in pixel system: pixel centers have integral indices\n */\nmath::Matrix4 geo2mask(const math::Extents2 &extents\n , const math::Size2 &gridSize)\n{\n math::Matrix4 trafo(boost::numeric::ublas::identity_matrix(4));\n\n auto es(size(extents));\n\n // scales\n math::Size2f scale(gridSize.width / es.width\n , gridSize.height / es.height);\n\n // scale to grid\n trafo(0, 0) = scale.width;\n trafo(1, 1) = -scale.height;\n\n // move to origin\n trafo(0, 3) = -extents.ll(0) * scale.width;\n trafo(1, 3) = extents.ur(1) * scale.height;\n\n return trafo;\n}\n\nvoid updateCoverage(Mesh::CoverageMask &cm, const SubMesh &sm\n , const math::Extents2 &sdsExtents\n , std::uint8_t smIndex)\n{\n const auto rasterSize(cm.size());\n auto trafo(geo2mask(sdsExtents, rasterSize));\n\n std::vector scanlines;\n cv::Point3f tri[3];\n for (const auto &face : sm.faces) {\n for (int i : { 0, 1, 2 }) {\n auto p(transform(trafo, sm.vertices[face[i]]));\n tri[i].x = p(0); tri[i].y = p(1); tri[i].z = p(2);\n }\n\n scanlines.clear();\n imgproc::scanConvertTriangle(tri, 0, rasterSize.height, scanlines);\n\n for (const auto &sl : scanlines) {\n imgproc::processScanline\n (sl, 0, rasterSize.width, [&](int x, int y, float)\n {\n cm.set(x, y, smIndex + 1);\n });\n }\n }\n}\n\n} // namespace\n\nvoid updateCoverage(Mesh &mesh, const SubMesh &sm\n , const math::Extents2 &sdsExtents\n , std::uint8_t smIndex)\n{\n updateCoverage(mesh.coverageMask, sm, sdsExtents, smIndex);\n}\n\nvoid generateCoverage(Mesh &mesh, const math::Extents2 &sdsExtents)\n{\n mesh.createCoverage(false);\n\n std::uint8_t smIndex(0);\n for (const auto &sm : mesh) {\n updateCoverage(mesh, sm, sdsExtents, smIndex++);\n }\n}\n\nvoid generateMeshMask(MeshMask &mask, const Mesh &mesh\n , const math::Extents2 &sdsExtents)\n{\n mask.createCoverage(false);\n mask.surfaceReferences.clear();\n\n std::uint8_t smIndex(0);\n for (const auto &sm : mesh) {\n updateCoverage(mask.coverageMask, sm, sdsExtents, smIndex++);\n mask.surfaceReferences.push_back(sm.surfaceReference);\n }\n}\n\n} } // namespace vtslibs::vts\n", "meta": {"hexsha": "c01764a3e21ece86c657d5bed0292f761fe6d334", "size": 4522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts/meshcoverage.cpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshcoverage.cpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshcoverage.cpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 30.7619047619, "max_line_length": 78, "alphanum_fraction": 0.6656346749, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1994332522251332}} {"text": "#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"./comparerLogic.h\"\n\nusing namespace std;\n\nusing namespace nil::crypto3::zk::components;\nusing namespace nil::crypto3::zk::snark;\n\n\nushort INVALID_PROOF_RETURN_CODE = 200;\n\nstd::string convert_byteblob_to_hex_string(std::vector blob) {\n // convert byte_blob to hex string and print it to output\n std::string hex;\n hex.reserve(blob.size() * 2);\n boost::algorithm::hex(blob.begin(), blob.end(), back_inserter(hex));\n return hex;\n}\n\nvoid save_byteblob(std::vector byteblob, boost::filesystem::path fname) {\n boost::filesystem::ofstream out(fname);\n for (const auto &v : byteblob) {\n out << v;\n }\n out.close();\n}\n\nstd::vector load_byteblob(boost::filesystem::path fname) {\n boost::filesystem::ifstream stream(fname, std::ios::in | std::ios::binary);\n std::vector contents((std::istreambuf_iterator(stream)), std::istreambuf_iterator());\n if (contents.size() == 0) {\n throw std::ios_base::failure(\"Empty file\");\n }\n return contents;\n}\n\n\n// proving key\n\nvoid save_proving_key(scheme_type::proving_key_type pk, boost::filesystem::path fname) {\n std::vector byteblob = nil::marshalling::verifier_input_serializer_tvm::process(pk);\n save_byteblob(byteblob, fname);\n}\n\nscheme_type::proving_key_type load_proving_key(boost::filesystem::path fname) {\n std::vector byteblob = load_byteblob(fname);\n nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n return nil::marshalling::verifier_input_deserializer_tvm::proving_key_process(\n byteblob.cbegin(),\n byteblob.cend(),\n processingStatus);\n}\n\n// verification key\n\nvoid save_verification_key(scheme_type::verification_key_type vk, boost::filesystem::path fname) {\n std::vector byteblob = nil::marshalling::verifier_input_serializer_tvm::process(vk);\n save_byteblob(byteblob, fname);\n}\n\nscheme_type::verification_key_type load_verification_key(boost::filesystem::path fname) {\n std::vector byteblob = load_byteblob(fname);\n nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n return nil::marshalling::verifier_input_deserializer_tvm::verification_key_process(\n byteblob.cbegin(),\n byteblob.cend(),\n processingStatus);\n}\n\n// proof\n\nvoid save_proof(scheme_type::proof_type proof, boost::filesystem::path fname) {\n std::vector byteblob = nil::marshalling::verifier_input_serializer_tvm::process(proof);\n save_byteblob(byteblob, fname);\n}\n\nscheme_type::proof_type load_proof(boost::filesystem::path fname) {\n std::vector byteblob = load_byteblob(fname);\n nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n return nil::marshalling::verifier_input_deserializer_tvm::proof_process(\n byteblob.cbegin(),\n byteblob.cend(),\n processingStatus);\n}\n\n\n// primary input\n\nvoid save_primary_input(zk::snark::r1cs_primary_input primary_input, boost::filesystem::path fname) {\n std::vector byteblob = nil::marshalling::verifier_input_serializer_tvm::process(primary_input);\n save_byteblob(byteblob, fname);\n}\n\nzk::snark::r1cs_primary_input load_primary_input(boost::filesystem::path fname) {\n std::vector byteblob = load_byteblob(fname);\n nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n return nil::marshalling::verifier_input_deserializer_tvm::primary_input_process(\n byteblob.cbegin(),\n byteblob.cend(),\n processingStatus);\n}\n\n\nint setup_keys(boost::filesystem::path pk_path, boost::filesystem::path vk_path) {\n\n blueprint bp;\n ComparerLogic comparerLogic(bp);\n comparerLogic.generate_r1cs_constraints(bp);\n\n cout << \"Blueprint size: \" << bp.num_variables() << endl;\n cout << \"Generating constraint system...\" << endl;\n const r1cs_constraint_system constraint_system = bp.get_constraint_system();\n cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n cout << \"Generating keypair...\" << endl;\n scheme_type::keypair_type keypair = generate(constraint_system);\n\n cout << \"Saving proving key to a file \" << pk_path<< endl;\n save_proving_key(keypair.first, pk_path);\n\n cout << \"Saving verification key to a file \" << vk_path << endl;\n save_verification_key(keypair.second, vk_path);\n\n return 0;\n}\n\nint create_proof(boost::filesystem::path pk_path, boost::filesystem::path proof_path, boost::filesystem::path pi_path, int minYear, int maxYear, int year) {\n\n cout << \"Loading proving key from a file \" << pk_path << endl;\n typename scheme_type::proving_key_type pk = load_proving_key(pk_path);\n\n blueprint bp;\n ComparerLogic comparerLogic(bp);\n\n cout << \"Generating constraint system...\" << endl;\n comparerLogic.generate_r1cs_constraints(bp);\n\n cout << \"Generating witness...\" << endl;\n comparerLogic.generate_r1cs_witness(bp, minYear, maxYear, year);\n\n cout << \"Blueprint is satisfied: \" << bp.is_satisfied() << endl;\n\n if (!bp.is_satisfied()) {\n return INVALID_PROOF_RETURN_CODE;\n }\n\n cout << \"Generating proof...\" << endl;\n const scheme_type::proof_type proof = prove(pk, bp.primary_input(), bp.auxiliary_input());\n\n cout << \"Saving proof to file \" << proof_path << endl;\n save_proof(proof, proof_path);\n\n cout << \"Saving primary input to file \" << pi_path << endl;\n save_primary_input(bp.primary_input(), pi_path);\n return 0;\n}\n\nint verify_proof(boost::filesystem::path proof_path, boost::filesystem::path vk_path, boost::filesystem::path pi_path) {\n\n cout << \"Loading proof from a file \" << proof_path << endl;\n typename scheme_type::proof_type proof = load_proof(proof_path);\n\n cout << \"Loading primary input from a file \" << pi_path << endl;\n r1cs_primary_input input = load_primary_input(pi_path);\n\n cout << \"Loading verification key from a file \" << vk_path << endl;\n typename scheme_type::verification_key_type vk = load_verification_key(vk_path);\n\n // verify\n using basic_proof_system = r1cs_gg_ppzksnark;\n const bool verified = verify(vk, input, proof);\n cout << \"Verification status: \" << verified << endl;\n\n return verified ? 0 : INVALID_PROOF_RETURN_CODE;\n}\n\nint main(int argc, char *argv[]) {\n int maxYear, minYear, year;\n boost::filesystem::path pk_path, vk_path, proof_path, pi_path;\n // bool hexFlag;\n\n boost::program_options::options_description options(\"CLI Proof Generator\");\n options.add_options()\n // (\"hex,h\", boost::program_options::bool_switch(&hexFlag), \"print only hex proof to output\")\n (\"minYear,minYear\", boost::program_options::value(&minYear)->default_value(0))\n (\"maxYear,maxYear\", boost::program_options::value(&maxYear)->default_value(100))\n (\"year,year\", boost::program_options::value(&year)->default_value(18))\n (\"proving-key-path,pk\", boost::program_options::value(&pk_path)->default_value(\"proving.key\"))\n (\"verification-key-path,vk\", boost::program_options::value(&vk_path)->default_value(\"verification.key\"))\n (\"proof-path,p\", boost::program_options::value(&proof_path)->default_value(\"proof\"))\n (\"primary-input-path,pi\", boost::program_options::value(&pi_path)->default_value(\"primary.input\"));\n\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).run(), vm);\n boost::program_options::notify(vm);\n\n cout << setprecision(16);\n\n if (!argv[1]) {\n cout << \"Please select a command: [setup/prove/verify]\" << endl;\n return 0;\n }\n else if (string(argv[1]) == \"setup\") {\n // Generate proving.key & verification.key\n return setup_keys(pk_path, vk_path);\n } else if (string(argv[1]) == \"prove\") {\n return create_proof(pk_path, proof_path, pi_path, minYear, maxYear, year);\n } else if (string(argv[1]) == \"verify\") {\n return verify_proof(proof_path, pi_path, vk_path);\n }\n\n return 0;\n}\n\n", "meta": {"hexsha": "1d889df6e208be6bd21c6658dea0e5cd212821f8", "size": 9043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/bin/main.cpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snark-logic/bin/main.cpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/bin/main.cpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 39.6622807018, "max_line_length": 156, "alphanum_fraction": 0.7160234435, "num_tokens": 2225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.19925680465702822}} {"text": "/**\n *****************************************************************************\n * @author This file is part of tinyram_snark, developed by SCIPR Lab\n * and contributors (see AUTHORS).\n * @copyright MIT license (see LICENSE file)\n *****************************************************************************/\n#include \n#include \n#ifndef MINDEPS\n#include \n#endif\n\n#include \n#include \n#include \n\n#ifndef MINDEPS\nnamespace po = boost::program_options;\n\nbool process_prover_command_line(const int argc, const char** argv,\n std::string &processed_assembly_fn,\n std::string &proving_key_fn,\n std::string &primary_input_fn,\n std::string &auxiliary_input_fn,\n std::string &proof_fn)\n{\n try\n {\n po::options_description desc(\"Usage\");\n desc.add_options()\n (\"help\", \"print this help message\")\n (\"processed_assembly\", po::value(&processed_assembly_fn)->required())\n (\"proving_key\", po::value(&proving_key_fn)->required())\n (\"primary_input\", po::value(&primary_input_fn)->required())\n (\"auxiliary_input\", po::value(&auxiliary_input_fn)->required())\n (\"proof\", po::value(&proof_fn)->required());\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if (vm.count(\"help\"))\n {\n std::cout << desc << \"\\n\";\n return false;\n }\n\n po::notify(vm);\n }\n catch(std::exception& e)\n {\n std::cerr << \"Error: \" << e.what() << \"\\n\";\n return false;\n }\n\n return true;\n}\n#endif\n\nusing namespace tinyram_snark;\n\nint main(int argc, const char * argv[])\n{\n default_tinyram_ppzksnark_pp::init_public_params();\n\n#ifdef MINDEPS\n std::string processed_assembly_fn = \"processed_assembly.txt\";\n std::string proving_key_fn = \"proving_key.txt\";\n std::string primary_input_fn = \"primary_input.txt\";\n std::string auxiliary_input_fn = \"auxiliary_input.txt\";\n std::string proof_fn = \"proof.txt\";\n#else\n std::string processed_assembly_fn;\n std::string proving_key_fn;\n std::string primary_input_fn;\n std::string auxiliary_input_fn;\n std::string proof_fn;\n\n if (!process_prover_command_line(argc, argv, processed_assembly_fn,\n proving_key_fn, primary_input_fn, auxiliary_input_fn, proof_fn))\n {\n return 1;\n }\n#endif\n libff::start_profiling();\n\n /* load everything */\n libff::enter_block(\"Deserialize proving key\");\n ram_ppzksnark_proving_key pk;\n std::ifstream pk_file(proving_key_fn);\n pk_file >> pk;\n pk_file.close();\n libff::leave_block(\"Deserialize proving key\");\n\n std::ifstream processed(processed_assembly_fn);\n tinyram_program program = load_preprocessed_program(pk.ap, processed);\n\n std::ifstream f_primary_input(primary_input_fn);\n std::ifstream f_auxiliary_input(auxiliary_input_fn);\n tinyram_input_tape primary_input = load_tape(f_primary_input);\n tinyram_input_tape auxiliary_input = load_tape(f_auxiliary_input);\n\n const ram_boot_trace boot_trace = tinyram_boot_trace_from_program_and_input(pk.ap, pk.primary_input_size_bound, program, primary_input);\n const ram_ppzksnark_proof proof = ram_ppzksnark_prover(pk, boot_trace, auxiliary_input);\n\n libff::enter_block(\"Serialize proof\");\n std::ofstream proof_file(proof_fn);\n proof_file << proof;\n proof_file.close();\n libff::leave_block(\"Serialize proof\");\n}\n", "meta": {"hexsha": "9c6250531311e4189fe6674ebd19e5a2710962b7", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_stars_repo_name": "alittlehorse/osprey", "max_stars_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T11:50:40.000Z", "max_issues_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_issues_repo_name": "alittlehorse/osprey", "max_issues_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tinyram_snark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_prover.cpp", "max_forks_repo_name": "alittlehorse/osprey", "max_forks_repo_head_hexsha": "22f290a7de3413a847e3dc33c96328752cc37f47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T15:50:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T15:50:15.000Z", "avg_line_length": 36.4594594595, "max_line_length": 170, "alphanum_fraction": 0.6419570052, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19925679704843258}} {"text": "/*\n\nCopyright (c) 2005-2017, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\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 * Neither the name of the University of Oxford nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n#ifndef DYNAMICALLY_LOADABLE_LR91_HPP_\n#define DYNAMICALLY_LOADABLE_LR91_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include \n\n#include \"AbstractCardiacCell.hpp\"\n#include \"AbstractStimulusFunction.hpp\"\n#include \"AbstractDynamicallyLoadableEntity.hpp\"\n#include \n\n/**\n * This class represents the Luo-Rudy 1991 system of equations,\n * with support for being compiled into a .so and loaded at run-time.\n */\nclass DynamicallyLoadableLr91 : public AbstractCardiacCell, public AbstractDynamicallyLoadableEntity\n{\nprivate:\n /** Needed for serialization. */\n friend class boost::serialization::access;\n /**\n * Archive the member variables.\n *\n * @param archive\n * @param version\n */\n template\n void serialize(Archive & archive, const unsigned int version)\n {\n archive & boost::serialization::base_object(*this);\n archive & boost::serialization::base_object(*this);\n }\n\n /* Constants for the model */\n\n /** membrane capcaitance*/\n static const double membrane_C;\n /** Faraday constant*/\n static const double membrane_F;\n /** Universal gas constant*/\n static const double membrane_R;\n /** Temeperature*/\n static const double membrane_T;\n /** Reversal potentila for background current*/\n static const double background_current_E_b;\n /** Maximal conductance for background current*/\n static const double background_current_g_b;\n /** Maximal conductance for sodium current*/\n static const double fast_sodium_current_g_Na;\n /** Intracellular potassium concentration*/\n static const double ionic_concentrations_Ki;\n /** Extracellular potassium concentration*/\n static const double ionic_concentrations_Ko;\n /** Intracellular sodium concentration*/\n static const double ionic_concentrations_Nai;\n /** Extracellular sodium concentration*/\n static const double ionic_concentrations_Nao;\n /** Maximal conductance for plateau current*/\n static const double plateau_potassium_current_g_Kp;\n /** Permeability ratio Na/K for potassium currents*/\n static const double time_dependent_potassium_current_PR_NaK;\n\n /** Another parameter, which is a function of the above */\n double fast_sodium_current_E_Na;\n\n /**\n * Range-checking on the current values of the state variables. Make sure\n * all gating variables have are within zero and one, and all concentrations\n * are positive\n */\n void VerifyStateVariables();\n\npublic:\n /**\n * Constructor\n *\n * @param pSolver is a pointer to the ODE solver\n * @param pIntracellularStimulus is a pointer to the intracellular stimulus\n */\n DynamicallyLoadableLr91(boost::shared_ptr pSolver,\n boost::shared_ptr pIntracellularStimulus);\n\n /**\n * Destructor\n */\n ~DynamicallyLoadableLr91();\n\n /**\n * Fill in a vector representing the RHS of the Luo-Rudy 1991 system\n * of Odes at each time step, y' = [y1' ... yn'].\n * Some ODE solver will call this function repeatedly to solve for y = [y1 ... yn].\n *\n * @param time the current time, in milliseconds\n * @param rY current values of the state variables\n * @param rDY to be filled in with derivatives\n */\n void EvaluateYDerivatives(double time, const std::vector &rY, std::vector &rDY);\n\n /**\n * Returns the ionic current\n *\n * @param pStateVariables optional state at which to evaluate the current\n * @return the total ionic current\n */\n double GetIIonic(const std::vector* pStateVariables=NULL);\n\n /**\n * Get the intracellular calcium concentration\n *\n * @return the intracellular calcium concentration\n */\n double GetIntracellularCalciumConcentration();\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(DynamicallyLoadableLr91)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a DynamicallyLoadableLr91 instance.\n */\ntemplate\ninline void save_construct_data(\n Archive & ar, const DynamicallyLoadableLr91 * t, const unsigned int file_version)\n{\n const boost::shared_ptr p_solver = t->GetSolver();\n const boost::shared_ptr p_stimulus = t->GetStimulusFunction();\n ar << p_solver;\n ar << p_stimulus;\n}\n\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a DynamicallyLoadableLr91 instance (using existing constructor).\n *\n * NB this constructor allocates memory for the other member variables too.\n */\ntemplate\ninline void load_construct_data(\n Archive & ar, DynamicallyLoadableLr91 * t, const unsigned int file_version)\n{\n\n boost::shared_ptr p_solver;\n boost::shared_ptr p_stimulus;\n ar >> p_solver;\n ar >> p_stimulus;\n ::new(t)DynamicallyLoadableLr91(p_solver, p_stimulus);\n}\n}\n} // namespace ...\n\n#endif // DYNAMICALLY_LOADABLE_LR91_HPP_\n", "meta": {"hexsha": "db29541aa4ab790498a2f7dea676522c73a5284e", "size": 6939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heart/dynamic/DynamicallyLoadableLr91.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3298429319, "max_line_length": 100, "alphanum_fraction": 0.7410289667, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}} {"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 \n#include \n\nusing namespace vw;\n\nVector3 cartography::GeodeticToCartesian::operator()( Vector3 const& v ) const {\n if ( boost::math::isnan(v[2]) )\n return Vector3();\n return m_datum.geodetic_to_cartesian(v);\n}\n\nVector3 cartography::CartesianToGeodetic::operator()( Vector3 const& v ) const {\n if ( v == Vector3() )\n return Vector3(0,0,std::numeric_limits::quiet_NaN());\n return m_datum.cartesian_to_geodetic(v);\n}\n\nVector3 cartography::GeodeticToProjection::operator()( Vector3 const& v ) const {\n if ( boost::math::isnan(v[2]) )\n return v;\n Vector2 pix = m_reference.lonlat_to_pixel( subvector(v, 0, 2) );\n return Vector3( pix[0], pix[1], v[2] );\n}\n\nVector3 cartography::ProjectionToGeodetic::operator()( Vector3 const& v ) const {\n Vector2 ll = m_reference.pixel_to_lonlat( subvector( v, 0, 2 ) );\n return Vector3( ll[0], ll[1], v[2] );\n}\n\nVector3 cartography::GeodeticToPoint::operator()( Vector3 const& v ) const {\n if ( boost::math::isnan(v[2]) )\n return v;\n Vector2 pix = m_reference.lonlat_to_point( subvector(v, 0, 2) );\n return Vector3( pix[0], pix[1], v[2] );\n}\n\nVector3 cartography::PointToGeodetic::operator()( Vector3 const& v ) const {\n Vector2 ll = m_reference.point_to_lonlat( subvector( v, 0, 2 ) );\n return Vector3( ll[0], ll[1], v[2] );\n}\n", "meta": {"hexsha": "e925f49edbcfa4c32a5e99f2700ba464212b59eb", "size": 2191, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Cartography/PointImageManipulation.cc", "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/Cartography/PointImageManipulation.cc", "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/Cartography/PointImageManipulation.cc", "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": 37.1355932203, "max_line_length": 81, "alphanum_fraction": 0.7161113647, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19908342551874725}} {"text": "// --------------------------------------------------------------------------\n// OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// * Neither the name of any author or any participating institution\n// may be used to endorse or promote products derived from this software\n// without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\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 ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Clemens Groepl $\n// $Authors: $\n// --------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace OpenMS\n{\n int EmgFitter1D::EgmFitterFunctor::operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)\n {\n Size n = m_data->n;\n EmgFitter1D::RawDataArrayType set = m_data->set;\n\n EmgFitter1D::CoordinateType h = x(0);\n EmgFitter1D::CoordinateType w = x(1);\n EmgFitter1D::CoordinateType s = x(2);\n EmgFitter1D::CoordinateType z = x(3);\n\n EmgFitter1D::CoordinateType Yi = 0.0;\n\n // iterate over all points of the signal\n for (Size i = 0; i < n; i++)\n {\n double t = set[i].getPos();\n\n // Simplified EMG\n Yi = (h * w / s) * sqrt(2.0 * Constants::PI) * exp((pow(w, 2) / (2 * pow(s, 2))) - ((t - z) / s)) / (1 + exp((-2.4055 / sqrt(2.0)) * (((t - z) / w) - w / s)));\n\n fvec(i) = Yi - set[i].getIntensity();\n }\n return 0;\n }\n\n // compute Jacobian matrix for the different parameters\n int EmgFitter1D::EgmFitterFunctor::df(const Eigen::VectorXd& x, Eigen::MatrixXd& J)\n {\n Size n = m_data->n;\n EmgFitter1D::RawDataArrayType set = m_data->set;\n\n EmgFitter1D::CoordinateType h = x(0);\n EmgFitter1D::CoordinateType w = x(1);\n EmgFitter1D::CoordinateType s = x(2);\n EmgFitter1D::CoordinateType z = x(3);\n\n const EmgFitter1D::CoordinateType emg_const = 2.4055;\n const EmgFitter1D::CoordinateType sqrt_2pi = sqrt(2 * Constants::PI);\n const EmgFitter1D::CoordinateType sqrt_2 = sqrt(2.0);\n\n EmgFitter1D::CoordinateType exp1, exp2, exp3 = 0.0;\n EmgFitter1D::CoordinateType derivative_height, derivative_width, derivative_symmetry, derivative_retention = 0.0;\n\n // iterate over all points of the signal\n for (Size i = 0; i < n; i++)\n {\n EmgFitter1D::CoordinateType t = set[i].getPos();\n\n exp1 = exp(((w * w) / (2 * s * s)) - ((t - z) / s));\n exp2 = (1 + exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s)));\n exp3 = exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s));\n\n // f'(h)\n derivative_height = w / s * sqrt_2pi * exp1 / exp2;\n\n // f'(h)\n derivative_width = h / s * sqrt_2pi * exp1 / exp2 + (h * w * w) / (s * s * s) * sqrt_2pi * exp1 / exp2 + (emg_const * h * w) / s * sqrt_2pi * exp1 * (-(t - z) / (w * w) - 1 / s) * exp3 / ((exp2 * exp2) * sqrt_2);\n\n // f'(s)\n derivative_symmetry = -h * w / (s * s) * sqrt_2pi * exp1 / exp2 + h * w / s * sqrt_2pi * (-(w * w) / (s * s * s) + (t - z) / (s * s)) * exp1 / exp2 + (emg_const * h * w * w) / (s * s * s) * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);\n\n // f'(z)\n derivative_retention = h * w / (s * s) * sqrt_2pi * exp1 / exp2 - (emg_const * h) / s * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);\n\n // set the jacobian matrix\n J(i, 0) = derivative_height;\n J(i, 1) = derivative_width;\n J(i, 2) = derivative_symmetry;\n J(i, 3) = derivative_retention;\n }\n return 0;\n }\n\n EmgFitter1D::EmgFitter1D() :\n LevMarqFitter1D()\n {\n setName(getProductName());\n defaults_.setValue(\"statistics:variance\", 1.0, \"Variance of the model.\", ListUtils::create(\"advanced\"));\n defaultsToParam_();\n }\n\n EmgFitter1D::EmgFitter1D(const EmgFitter1D& source) :\n LevMarqFitter1D(source)\n {\n setParameters(source.getParameters());\n updateMembers_();\n }\n\n EmgFitter1D::~EmgFitter1D()\n {\n }\n\n EmgFitter1D& EmgFitter1D::operator=(const EmgFitter1D& source)\n {\n if (&source == this)\n return *this;\n\n LevMarqFitter1D::operator=(source);\n setParameters(source.getParameters());\n updateMembers_();\n\n return *this;\n }\n\n EmgFitter1D::QualityType EmgFitter1D::fit1d(const RawDataArrayType& set, InterpolationModel*& model)\n {\n // Calculate bounding box\n CoordinateType min_bb = set[0].getPos(), max_bb = set[0].getPos();\n for (Size pos = 1; pos < set.size(); ++pos)\n {\n CoordinateType tmp = set[pos].getPos();\n if (min_bb > tmp)\n min_bb = tmp;\n if (max_bb < tmp)\n max_bb = tmp;\n }\n\n // Enlarge the bounding box by a few multiples of the standard deviation\n const CoordinateType stdev = sqrt(statistics_.variance()) * tolerance_stdev_box_;\n min_bb -= stdev;\n max_bb += stdev;\n\n\n // Set advanced parameters for residual_ und jacobian_ method\n EmgFitter1D::Data d;\n d.n = set.size();\n d.set = set;\n\n // Compute start parameters\n setInitialParameters_(set);\n\n // Optimize parameter with Levenberg-Marquardt algorithm\n// CoordinateType x_init[4] = { height_, width_, symmetry_, retention_ };\n Eigen::VectorXd x_init(4);\n x_init(0) = height_;\n x_init(1) = width_;\n x_init(2) = symmetry_;\n x_init(3) = retention_;\n if (symmetric_ == false)\n {\n EgmFitterFunctor functor(4, &d);\n optimize_(x_init, functor);\n }\n\n // Set optimized parameters\n height_ = x_init[0];\n width_ = x_init[1];\n symmetry_ = x_init[2];\n retention_ = x_init[3];\n\n#ifdef DEBUG_FEATUREFINDER\n if (getGslStatus_() != \"success\")\n {\n std::cout << \"status: \" << getGslStatus_() << std::endl;\n }\n#endif\n\n // build model\n model = static_cast(Factory >::create(\"EmgModel\"));\n model->setInterpolationStep(interpolation_step_);\n\n Param tmp;\n tmp.setValue(\"bounding_box:min\", min_bb);\n tmp.setValue(\"bounding_box:max\", max_bb);\n tmp.setValue(\"statistics:variance\", statistics_.variance());\n tmp.setValue(\"statistics:mean\", statistics_.mean());\n tmp.setValue(\"emg:height\", height_);\n tmp.setValue(\"emg:width\", width_);\n tmp.setValue(\"emg:symmetry\", symmetry_);\n tmp.setValue(\"emg:retention\", retention_);\n model->setParameters(tmp);\n\n\n // calculate pearson correlation\n std::vector real_data;\n real_data.reserve(set.size());\n std::vector model_data;\n model_data.reserve(set.size());\n\n for (Size i = 0; i < set.size(); ++i)\n {\n real_data.push_back(set[i].getIntensity());\n model_data.push_back(model->getIntensity(DPosition<1>(set[i].getPosition())));\n }\n\n QualityType correlation = Math::pearsonCorrelationCoefficient(real_data.begin(), real_data.end(), model_data.begin(), model_data.end());\n if (boost::math::isnan(correlation))\n correlation = -1.0;\n\n return correlation;\n }\n\n void EmgFitter1D::setInitialParameters_(const RawDataArrayType& set)\n {\n // sum over all intensities\n CoordinateType sum = 0.0;\n for (Size i = 0; i < set.size(); ++i)\n sum += set[i].getIntensity();\n\n // calculate the median\n Size median = 0;\n float count = 0.0;\n for (Size i = 0; i < set.size(); ++i)\n {\n count += set[i].getIntensity();\n if (count <= sum / 2)\n median = i;\n }\n\n // calculate the height of the peak\n height_ = set[median].getIntensity();\n\n // calculate retention time\n retention_ = set[median].getPos();\n\n // default is an asymmetric peak\n symmetric_ = false;\n\n // calculate the symmetry (fronted peak: s<1 , tailed peak: s>1)\n symmetry_ = fabs(set[set.size() - 1].getPos() - set[median].getPos()) / fabs(set[median].getPos() - set[0].getPos());\n\n // check the symmetry\n if (boost::math::isinf(symmetry_) || boost::math::isnan(symmetry_))\n {\n symmetric_ = true;\n symmetry_ = 10;\n }\n\n // optimize the symmetry\n // The computations can lead to an overflow error at very low values of symmetry (s~0).\n // For s~5 the parameter can be approximated by the Levenberg-Marquardt algorithms.\n // (the other parameters are much greater than one)\n if (symmetry_ < 1)\n symmetry_ += 5;\n\n // calculate the width of the peak\n // rt-values with intensity zero are not allowed for calculation of the width\n // normally: width_ = fabs( set[set.size() - 1].getPos() - set[0].getPos() );\n // but its better for the emg function to proceed from narrow peaks\n width_ = symmetry_;\n }\n\n void EmgFitter1D::updateMembers_()\n {\n LevMarqFitter1D::updateMembers_();\n statistics_.setVariance(param_.getValue(\"statistics:variance\"));\n }\n\n}\n", "meta": {"hexsha": "fd7fd650cec18f6fc1381153c274371e6d2fd576", "size": 10382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "Apache-2.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.3129251701, "max_line_length": 246, "alphanum_fraction": 0.6230013485, "num_tokens": 2939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19900810574626762}} {"text": "// Copyright (c) 2019, The Graft Project\n//\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//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n// conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n// of conditions and the following disclaimer in the documentation and/or other\n// materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n// 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\n// EXPRESS 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\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include \n#include \"cryptmsg.h\"\n#include \"crypto/chacha.h\"\n\nnamespace {\n\nstatic_assert(201103L <= __cplusplus, \"C++11 compiler required\");\n\n#if 0\n//can be used to check manually\n#define native_to_little boost::endian::native_to_big\n#define little_to_native boost::endian::big_to_native\n#else\nusing namespace boost::endian;\n#endif\n\ninline size_t getEncryptChachaSize(size_t plainSize)\n{\n return plainSize + sizeof(crypto::chacha_iv);\n}\n\nvoid encryptChacha(const uint8_t* plain, size_t plain_size, const crypto::secret_key &skey, uint8_t* cipher)\n{\n crypto::chacha_key key;\n crypto::generate_chacha_key(&skey, sizeof(skey), key);\n crypto::chacha_iv& iv = *reinterpret_cast(cipher);\n iv = crypto::rand();\n crypto::chacha8(plain, plain_size, key, iv, reinterpret_cast(cipher) + sizeof(iv));\n}\n\nvoid decryptChacha(const uint8_t* cipher, size_t cipher_size, const crypto::secret_key &skey, uint8_t* plain)\n{\n const size_t prefix_size = sizeof(crypto::chacha_iv);\n crypto::chacha_key key;\n crypto::generate_chacha_key(&skey, sizeof(skey), key);\n const crypto::chacha_iv &iv = *reinterpret_cast(cipher);\n crypto::chacha8(reinterpret_cast(cipher) + sizeof(iv), cipher_size - prefix_size, key, iv, reinterpret_cast(plain));\n}\n\nconstexpr uint8_t cStart = 0xA5;\nconstexpr uint8_t cEnd = 0x5A;\n\n#pragma pack(push, 1)\n\n//Note, native order is little-endian\n\n//SessionX in decrypted form contains session key x and constants to check that the decryption was correct\nstruct SessionX\n{\n uint8_t cstart; //decrypted value cStart\n crypto::secret_key x;\n uint8_t cend; //decrypted value cEnd\n};\n\nstruct XEntry\n{\n uint32_t Bhash; //xor of B\n uint8_t cipherX[sizeof(SessionX) + sizeof(crypto::chacha_iv)]; //encrypted SessionX\n};\n\nstruct CryptoMessageHead\n{\n uint32_t plainSize; //size of decrypted data\n crypto::public_key R; //random key used to encrypt session key\n uint16_t count; //recipients count\n XEntry xentries[1];\n};\n\n#pragma pack(pop)\n\nuint32_t getBhash(const crypto::public_key& B)\n{\n uint32_t res = 0;\n static_assert(sizeof(B) % sizeof(res) == 0, \"public key size must be a multiple of 4\");\n const uint32_t* p = reinterpret_cast(&B);\n for(int i = 0, cnt = sizeof(B) / sizeof(res); i < cnt; ++i, ++p)\n {\n res ^= *p;\n }\n return native_to_little(res);\n}\n\n/*!\n * \\brief encryptMsg - encrypts data for recipients using their B public keys (assumed public view keys).\n *\n * The result has following structure [plainSize:32][R:32][count of XEntrys:16][XEntry]...[XEntry][x encrypted data:+8*8]\n * plainSize - size of original data, x encrypted data takes 8 more bytes\n * [XEntry] - [Bhash:32][rBX] pair for each recipient\n * where Bhash - xor of B (aka fingerprint of B, using which recipient can find his entry)\n * [rBX:+8*8] - encrypted X (aka SessionX)\n * [X] = [cstart:8][x:32*8][cend:8]\n *\n * \\param inputSize - input buffer size.\n * \\param input - input buffer to encrypt.\n * \\param BkeysCount - count of B keys.\n * \\param Bkeys - array of B keys for each recipients.\n * \\param outputSize - output buffer size.\n * \\param output - output buffer.\n * \\returns output size required if output==nullptr or outputSize is not enough.\n * returns 0 on error\n */\n\nsize_t encryptMsg(size_t inputSize, const uint8_t* input, size_t BkeysCount, const crypto::public_key* Bkeys, size_t outputSize, uint8_t* output)\n{\n if(!inputSize || !BkeysCount)\n return 0;\n\n //prepare\n size_t msgHeadSize = sizeof(CryptoMessageHead) + (BkeysCount - 1) * sizeof(XEntry);\n size_t msgSize = msgHeadSize + getEncryptChachaSize(inputSize);\n if(outputSize < msgSize)\n return msgSize;\n if(!input || !Bkeys || !output)\n return 0;\n\n //make decorated session key\n SessionX X; X.cstart = cStart; X.cend = cEnd;\n //generate session key X.x\n {\n crypto::public_key tmpX;\n crypto::generate_keys(tmpX,X.x);\n }\n //chacha encrypt input with x\n encryptChacha(input, inputSize, X.x, output + msgHeadSize);\n\n //fill head\n CryptoMessageHead& head = *reinterpret_cast(output);\n head.plainSize = native_to_little(uint32_t(inputSize));\n crypto::secret_key r;\n crypto::generate_keys(head.R, r);\n head.count = native_to_little(uint16_t(BkeysCount));\n //fill XEntry for each B\n const crypto::public_key* pB = Bkeys;\n XEntry* pxe = head.xentries;\n for(size_t i=0; i(&X), sizeof(X), rB, xe.cipherX);\n }\n return msgSize;\n}\n\n/*!\n * \\brief decryptMsg - (reverse of encryptMsg) decrypts data for one of the recipients using his secret key b.\n *\n * \\param inputSize - input buffer size.\n * \\param input - input buffer to decrypt.\n * \\param bkey - secret key corresponding to one of Bs that were used to encrypt.\n * \\param outputSize - output buffer size.\n * \\param output - output buffer.\n * \\returns output size required if output==nullptr or outputSize is not enough\n * returns 0 on error\n */\n\nsize_t decryptMsg(size_t inputSize, const uint8_t* input, const crypto::secret_key& bkey, size_t outputSize, uint8_t* output)\n{\n if(!input || inputSize <= sizeof(CryptoMessageHead))\n return 0;\n //prepare\n const CryptoMessageHead& head = *reinterpret_cast(input);\n size_t head_count = little_to_native(head.count);\n size_t head_plainSize = little_to_native(head.plainSize);\n size_t msgHeadSize = sizeof(CryptoMessageHead) + ((size_t)(head_count - 1)) * sizeof(XEntry);\n size_t msgSize = msgHeadSize + getEncryptChachaSize(head_plainSize);\n if(inputSize < msgSize)\n return 0;\n if(outputSize < head_plainSize)\n return head_plainSize;\n if(!output)\n return 0;\n\n //get Bhash from b\n const crypto::secret_key& b = bkey;\n uint32_t Bhash;\n {\n crypto::public_key B;\n bool res = crypto::secret_key_to_public_key(bkey, B);\n if(!res) return false; //corrupted key\n Bhash = getBhash(B);\n }\n //find XEntry for B\n const XEntry* pxe = head.xentries;\n for(size_t i=0; i(&X));\n if(X.cstart != cStart || X.cend != cEnd) continue;\n //decrypt with session key\n decryptChacha(input + msgHeadSize, getEncryptChachaSize(head_plainSize), X.x, output);\n return head_plainSize;\n }\n return 0;\n}\n\n} //namespace\n\nnamespace graft { namespace crypto_tools {\n\nvoid encryptMessage(const std::string& input, const std::vector& Bkeys, std::string& output)\n{\n assert(!input.empty());\n //get output size\n size_t size = encryptMsg( input.size(), nullptr, Bkeys.size(), nullptr, 0, nullptr);\n assert(0(input.data()),\n Bkeys.size(), &Bkeys[0],\n output.size(), reinterpret_cast(&output[0]));\n assert(res == size);\n}\n\nvoid encryptMessage(const std::string& input, const crypto::public_key& Bkey, std::string& output)\n{\n std::vector v(1, Bkey);\n encryptMessage(input, v, output);\n}\n\nbool decryptMessage(const std::string& input, const crypto::secret_key& bkey, std::string& output)\n{\n assert(!input.empty());\n //get output size\n size_t size = decryptMsg( input.size(), reinterpret_cast(input.data()), bkey, 0, nullptr);\n if(!size)\n {\n output.clear();\n return false;\n }\n output.resize(size);\n //encrypt\n size_t res = decryptMsg( input.size(), reinterpret_cast(input.data()),\n bkey, output.size(), reinterpret_cast(&output[0]));\n if(!res)\n {\n output.clear();\n return false;\n }\n assert(res == size);\n return true;\n}\n\n}} //namespace graft::crypto_tools\n\n", "meta": {"hexsha": "21c12fa4665bcec6ae5c0443aab97d96896a6bcf", "size": 10329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/cryptmsg.cpp", "max_stars_repo_name": "Fez29/GraftNetwork", "max_stars_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T09:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-03T09:05:40.000Z", "max_issues_repo_path": "src/utils/cryptmsg.cpp", "max_issues_repo_name": "Fez29/GraftNetwork", "max_issues_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/cryptmsg.cpp", "max_forks_repo_name": "Fez29/GraftNetwork", "max_forks_repo_head_hexsha": "75c55efdc6f77d7c10639425e695a955e6e59798", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T06:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T06:59:14.000Z", "avg_line_length": 35.7404844291, "max_line_length": 145, "alphanum_fraction": 0.6870945881, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19873420851062892}} {"text": "#include \n#include \n\n#include \n\n#include \"caffe/common.hpp\"\n#include \"caffe/quantizer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\n\n#ifdef USE_GEMMLOWP\n#include \"public/gemmlowp.h\"\n#endif\n\nnamespace caffe {\n\ntemplate\ntypename std::enable_if::value, bool>::type\ngemmlowp_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const Dtype alpha, const Dtype* A,\n const Dtype* B, const Dtype beta, Dtype* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n // No gemmlowp available\n return false;\n}\n\n#ifdef USE_GEMMLOWP\ntemplate<>\ntypename std::enable_if::value, bool>::type\ngemmlowp_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const uint8_t alpha, const uint8_t* A,\n const uint8_t* B, const uint8_t beta, uint8_t* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n CHECK(a_quant && b_quant && c_quant)\n << \"Integer type requires quantization values.\";\n if (alpha == 1 && beta == 0 && alpha_quant == nullptr\n && beta_quant == nullptr) {\n const int32_t lhs_offset = -a_quant->get_zero();\n const int32_t rhs_offset = -b_quant->get_zero();\n\n gemmlowp::OutputStageQuantizeDownInt32ByFixedPoint quantize_down_stage;\n quantize_down_stage.result_offset_after_shift =\n c_quant->get_zero();\n\n int32_t mult;\n int8_t shift;\n\n QuantizerBase::template MultiplicativeQuantVals(\n a_quant, b_quant, c_quant, &mult, &shift);\n\n quantize_down_stage.result_fixedpoint_multiplier = mult;\n quantize_down_stage.result_shift = static_cast(shift);\n\n if (quantize_down_stage.result_shift < 0) {\n // Gemmlowp doesn't handle negative exponents\n return false;\n }\n\n gemmlowp::OutputStageSaturatingCastToUint8 saturating_cast_stage;\n const auto& output_pipeline =\n std::make_tuple(quantize_down_stage, saturating_cast_stage);\n\n gemmlowp::GemmContext gemm_context;\n\n gemmlowp::MatrixMap rs(C, M, N);\n\n if (trans_A == CblasNoTrans && trans_B == CblasNoTrans) {\n gemmlowp::MatrixMap\n lhs(A, M, K);\n gemmlowp::MatrixMap\n rhs(B, K, N);\n gemmlowp::GemmWithOutputPipeline(\n &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n } else if (trans_A == CblasNoTrans && trans_B == CblasTrans) {\n gemmlowp::MatrixMap\n lhs(A, M, K);\n gemmlowp::MatrixMap\n rhs(B, K, N);\n gemmlowp::GemmWithOutputPipeline(\n &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n } else if (trans_A == CblasTrans && trans_B == CblasNoTrans) {\n gemmlowp::MatrixMap\n lhs(A, M, K);\n gemmlowp::MatrixMap\n rhs(B, K, N);\n gemmlowp::GemmWithOutputPipeline(\n &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n } else {\n gemmlowp::MatrixMap\n lhs(A, M, K);\n gemmlowp::MatrixMap\n rhs(B, K, N);\n gemmlowp::GemmWithOutputPipeline(\n &gemm_context, lhs, rhs, &rs, lhs_offset, rhs_offset, output_pipeline);\n }\n return true;\n }\n // Gemmlowp can't handle the case\n return false;\n}\n#endif // USE_GEMMLOWP\n\n\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const Dtype alpha, const Dtype* A,\n const Dtype* B, const Dtype beta, Dtype* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n CHECK(a_quant && b_quant && c_quant)\n << \"Integer type requires quantization values.\";\n\n if (gemmlowp_gemm(trans_A, trans_B, M, N, K, alpha, A, B, beta, C,\n alpha_quant, a_quant, b_quant, beta_quant, c_quant)) {\n // Handled by gemmlowp implementation\n return;\n }\n\n typedef typename std::conditional::type>::type Difftype;\n typedef typename std::conditional::type Acctype;\n\n // std::cout << \"Difftype: \" << sizeof(Difftype) << std::endl;\n // std::cout << \"Acctype: \" << sizeof(Acctype) << std::endl;\n\n int8_t shift_bits = (32 / sizeof(Dtype)) - 1;\n\n int32_t mult;\n int8_t shift;\n int32_t alpha_mult;\n int8_t alpha_shift;\n int32_t beta_mult;\n int8_t beta_shift;\n Acctype c_max = c_quant->get_max();\n Acctype c_min = c_quant->get_min();\n Dtype lhs_off = a_quant->get_zero();\n Dtype rhs_off = b_quant->get_zero();\n Dtype alpha_off = alpha_quant ? alpha_quant->get_zero() : Dtype(0);\n Dtype beta_off = beta_quant ? beta_quant->get_zero() : Dtype(0);\n const Acctype result_off = c_quant->get_zero();\n\n QuantizerBase::template MultiplicativeQuantVals(\n a_quant, b_quant, c_quant, &mult, &shift, shift_bits);\n QuantizerBase::template MultiplicativeQuantVals(\n c_quant, alpha_quant, c_quant, &alpha_mult, &alpha_shift, shift_bits);\n QuantizerBase::template MultiplicativeQuantVals(\n c_quant, beta_quant, c_quant, &beta_mult, &beta_shift, shift_bits);\n\n int_tp inc_a = (trans_A == CblasNoTrans) ? 1 : M;\n int_tp inc_b = (trans_B == CblasNoTrans) ? N : 1;\n for (int_tp m = 0; m < M; ++m) {\n#pragma omp parallel for\n for (int_tp n = 0; n < N; ++n) {\n Acctype acc = Acctype(0);\n int_tp b_index = trans_B == CblasNoTrans ? n : K * n;\n int_tp a_index = trans_A == CblasNoTrans ? K * m : m;\n for (int_tp k = 0; k < K; ++k) {\n Difftype a_diff = A[a_index] - lhs_off;\n Difftype b_diff = B[b_index] - rhs_off;\n // std::cout << \"a_diff: \" << a_diff << std::endl;\n // std::cout << \"b_diff: \" << b_diff << std::endl;\n acc += static_cast(a_diff) * static_cast(b_diff);\n a_index += inc_a;\n b_index += inc_b;\n }\n Acctype reg = acc * (alpha_quant ? Acctype(1) : alpha);\n // std::cout << \"1: \" << m << \", \"<< n << \": \" << reg << std::endl;\n // std::cout << \"M: \" << mult << std::endl;\n // std::cout << \"S: \" << static_cast(shift_bits) << std::endl;\n reg = static_cast((static_cast(reg) *\n static_cast(mult)) / (1ll << shift_bits));\n // std::cout << \"2: \" << m << \", \"<< n << \": \" << reg << std::endl;\n if (shift >= 0) {\n reg = reg >> shift;\n } else {\n reg = reg << -shift;\n }\n if (alpha_quant) {\n Difftype alpha_diff = alpha - alpha_off;\n reg = static_cast(alpha_diff) * static_cast(reg);\n reg = static_cast((static_cast(reg) *\n static_cast(alpha_mult)) / (1ll << shift_bits));\n if (alpha_shift >= 0) {\n reg = reg >> alpha_shift;\n } else {\n reg = reg << -alpha_shift;\n }\n }\n // std::cout << \"3: \" << m << \", \"<< n << \": \" << reg << std::endl;\n if (beta_quant) {\n Difftype beta_diff = beta - beta_off;\n Difftype c_diff = C[m * N + n] - static_cast(result_off);\n Acctype creg = static_cast(beta_diff)\n * static_cast(c_diff);\n creg = static_cast((static_cast(creg) *\n static_cast(beta_mult)) / (1ll << shift_bits));\n if (beta_shift >= 0) {\n creg = creg >> beta_shift;\n } else {\n creg = creg << -beta_shift;\n }\n reg = reg + creg;\n } else if (beta == Dtype(1)) {\n reg = reg + (C[m * N + n] - result_off);\n }\n reg = reg + result_off;\n // std::cout << \"4: \" << m << \", \"<< n << \": \" << reg << std::endl;\n C[m * N + n] = static_cast(std::min(std::max(reg, c_min), c_max));\n }\n }\n}\n\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const Dtype alpha, const Dtype* A,\n const Dtype* B, const Dtype beta, Dtype* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n int_tp inc_a = (trans_A == CblasNoTrans) ? 1 : M;\n int_tp inc_b = (trans_B == CblasNoTrans) ? N : 1;\n for (int_tp m = 0; m < M; ++m) {\n#pragma omp parallel for\n for (int_tp n = 0; n < N; ++n) {\n Dtype acc = 0;\n int_tp b_index = trans_B == CblasNoTrans ? n : K * n;\n int_tp a_index = trans_A == CblasNoTrans ? K * m : m;\n for (int_tp k = 0; k < K; ++k) {\n acc += A[a_index] * B[b_index];\n a_index += inc_a;\n b_index += inc_b;\n }\n if (beta != 0) {\n C[m * N + n] = acc * alpha + beta * C[m * N + n];\n }\n else {\n C[m * N + n] = acc * alpha;\n }\n }\n }\n}\n\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const half_fp alpha, const half_fp* A,\n const half_fp* B, const half_fp beta, half_fp* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const uint8_t alpha, const uint8_t* A,\n const uint8_t* B, const uint8_t beta, uint8_t* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const uint16_t alpha, const uint16_t* A,\n const uint16_t* B, const uint16_t beta, uint16_t* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const uint32_t alpha, const uint32_t* A,\n const uint32_t* B, const uint32_t beta, uint32_t* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant);\ntemplate\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A, const CBLAS_TRANSPOSE trans_B,\n const int_tp M, const int_tp N, const int_tp K,\n const uint64_t alpha, const uint64_t* A,\n const uint64_t* B, const uint64_t beta, uint64_t* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant);\n\n\ntemplate<>\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A,\n const CBLAS_TRANSPOSE trans_B, const int_tp M,\n const int_tp N, const int_tp K, const float alpha,\n const float* A, const float* B, const float beta,\n float* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n int_tp lda = (trans_A == CblasNoTrans) ? K : M;\n int_tp ldb = (trans_B == CblasNoTrans) ? N : K;\n cblas_sgemm(CblasRowMajor, trans_A, trans_B, M, N, K, alpha, A, lda, B, ldb,\n beta, C, N);\n}\n\ntemplate<>\ntypename std::enable_if::value, void>::type\ncaffe_gemm(const CBLAS_TRANSPOSE trans_A,\n const CBLAS_TRANSPOSE trans_B, const int_tp M,\n const int_tp N, const int_tp K, const double alpha,\n const double* A, const double* B, const double beta,\n double* C,\n const QuantizerValues* const alpha_quant,\n const QuantizerValues* const a_quant,\n const QuantizerValues* const b_quant,\n const QuantizerValues* const beta_quant,\n const QuantizerValues* const c_quant) {\n int_tp lda = (trans_A == CblasNoTrans) ? K : M;\n int_tp ldb = (trans_B == CblasNoTrans) ? N : K;\n cblas_dgemm(CblasRowMajor, trans_A, trans_B, M, N, K, alpha, A, lda, B, ldb,\n beta, C, N);\n}\n\n} // namespace caffe\n\n", "meta": {"hexsha": "22f2132a9b9cfac5717bed60be36a9feb17da95c", "size": 16154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_blas_3.cpp", "max_stars_repo_name": "naibaf7/caffe", "max_stars_repo_head_hexsha": "29960153c828820b1abb55a5792283742f57caa2", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T01:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T17:03:28.000Z", "max_issues_repo_path": "src/caffe/util/math_blas_3.cpp", "max_issues_repo_name": "Miaomz/caffe-opencl", "max_issues_repo_head_hexsha": "505693d54298b89cf83b54778479087cff2f3bd6", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T13:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T05:00:10.000Z", "max_forks_repo_path": "src/caffe/util/math_blas_3.cpp", "max_forks_repo_name": "Miaomz/caffe-opencl", "max_forks_repo_head_hexsha": "505693d54298b89cf83b54778479087cff2f3bd6", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-07-05T17:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T13:16:02.000Z", "avg_line_length": 44.3791208791, "max_line_length": 80, "alphanum_fraction": 0.6038752012, "num_tokens": 4213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.19863873981225974}} {"text": "#include \n#include \n#include \n#include \n#include \n//#include \n//#include \n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\nclass Physics;\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#include \"vector_x86.hpp\"\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n SPHAnalysis() {\n this->id = 0;\n this->istar = 0;\n this->mass = 0.;\n this->pos = 0.;\n this->vel = 0.;\n this->uene = 0.;\n this->alph = 0.;\n this->alphu = 0.;\n this->ksr = 0.;\n for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n this->cmps[k] = 0.;\n } \n }\n\n void readAscii(FILE * fp) {\n fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass); // 3\n fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); // 6\n fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); // 9\n fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu); // 15\n fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr, &this->np); // 18\n fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp); // 21\n fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt); // 24\n fscanf(fp, \"%lf%lf%lf\", &this->pot, &this->abar, &this->zbar); // 27\n fscanf(fp, \"%lf\", &this->enuc); // 28\n fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc); // 31\n for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) { // 32 -- 44\n fscanf(fp, \"%lf\", &this->cmps[k]);\n }\n fscanf(fp, \"%lf\", &this->pot3);\n fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n fscanf(fp, \"%lf\", &this->entr);\n }\n\n /*\n void write(FILE * fp = stdout) {\n fprintf(fp, \"%8d %2d %+e\", this->id, this->istar, this->mass);\n fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]);\n fprintf(fp, \" %+e %+e %+e\", this->vel[0], this->vel[1], this->vel[2]);\n fprintf(fp, \" %+e %+e %+e\", this->uene, this->alph, this->alphu);\n fprintf(fp, \" %+e\", this->ksr);\n for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n fprintf(fp, \" %+.3e\", this->cmps[k]);\n }\n fprintf(fp, \"\\n\");\n }\n */\n\n inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n PS::F64mat qq = 0.;\n PS::F64vec dx = this->pos - xc;\n PS::F64 r2 = dx * dx;\n qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n qq.xy = this->mass * ( - dx[0] * dx[1]);\n qq.xz = this->mass * ( - dx[0] * dx[2]);\n qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n qq.yz = this->mass * ( - dx[1] * dx[2]);\n qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n return qq;\n }\n\n void copyFromForce(const Physics & physics);\n};\n\nclass BlackHoleNeutronStarAnalysis : public BlackHoleNeutronStar {\npublic:\n BlackHoleNeutronStarAnalysis() {\n this->id = 0;\n this->istar = 0;\n this->mass = 0.;\n this->pos = 0.;\n this->vel = 0.;\n this->acc = 0.;\n this->eps = 0.;\n this->pot = 0.;\n }\n\n void readAscii(FILE * fp) {\n fscanf(fp, \"%lld%lld%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf\",\n &this->id, &this->istar, &this->mass,\n &this->pos[0], &this->pos[1], &this->pos[2],\n &this->vel[0], &this->vel[1], &this->vel[2],\n &this->acc[0], &this->acc[1], &this->acc[2],\n &this->eps, &this->pot);\n }\n\n inline PS::F64mat calcMomentOfInertia(PS::F64vec xc) {\n PS::F64mat qq = 0.;\n PS::F64vec dx = this->pos - xc;\n PS::F64 r2 = dx * dx;\n qq.xx = this->mass * (r2 - dx[0] * dx[0]);\n qq.xy = this->mass * ( - dx[0] * dx[1]);\n qq.xz = this->mass * ( - dx[0] * dx[2]);\n qq.yy = this->mass * (r2 - dx[1] * dx[1]);\n qq.yz = this->mass * ( - dx[1] * dx[2]);\n qq.zz = this->mass * (r2 - dx[2] * dx[2]);\n return qq;\n }\n};\n\nclass MeshData : public SPHAnalysis {\npublic:\n PS::F64 tempu;\n\n MeshData() {\n this->id = 0;\n this->istar = 0;\n this->mass = 0.;\n this->pos = 0.;\n this->vel = 0.;\n this->uene = 0.;\n this->alph = 0.;\n this->alphu = 0.;\n this->ksr = 0.;\n for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n this->cmps[k] = 0.;\n } \n }\n\n void writeAscii(FILE *fp) {\n fprintf(fp, \"%8d\", this->id);\n fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]);\n fprintf(fp, \" %+e %+e %+e\", this->dens, this->temp, this->tempu);\n fprintf(fp, \" %+e\", this->vsnd);\n fprintf(fp, \"\\n\");\n }\n\n void copyFromForce(const Physics & physics);\n};\n\ntemplate \nvoid generateMeshData(Tmesh & mesh) {\n if(PS::Comm::getRank() != 0) {\n return;\n }\n PS::F64 xmin = -5e8;\n PS::F64 xmax = +5e8;\n PS::S64 nx = 100;\n PS::S64 nx3 = nx * nx * nx;\n PS::F64 dx = (xmax - xmin) / (PS::F64)nx;\n mesh.setNumberOfParticleLocal(nx3);\n for(PS::S64 i = 0; i < nx; i++) {\n for(PS::S64 j = 0; j < nx; j++) {\n for(PS::S64 k = 0; k < nx; k++) {\n PS::S64 id = i * nx * nx + j * nx + k;\n mesh[id].id = id;\n mesh[id].mass = 0.;\n mesh[id].pos[0] = xmin + dx * (PS::F64)i;\n mesh[id].pos[1] = xmin + dx * (PS::F64)j;\n mesh[id].pos[2] = xmin + dx * (PS::F64)k;\n mesh[id].ksr = 1e7;\n mesh[id].dens = 0.;\n mesh[id].temp = 0.;\n }\n }\n }\n}\n\nclass Physics {\npublic:\n PS::F64 dens;\n PS::F64 temp;\n PS::F64 uene;\n void clear() {\n dens = 0.;\n temp = 0.;\n uene = 0.;\n }\n};\n\nvoid SPHAnalysis::copyFromForce(const Physics & physics) {\n this->dens = physics.dens;\n this->temp = physics.temp;\n this->uene = physics.uene;\n}\n\nvoid MeshData::copyFromForce(const Physics & physics) {\n this->dens = physics.dens;\n this->temp = physics.temp;\n this->uene = physics.uene;\n}\n\nclass PhysicsEPI {\npublic:\n PS::S32 id;\n PS::F64 mass;\n PS::F64vec pos;\n bool meshornot;\n\n void copyFromFP(const SPHAnalysis & sph) {\n this->id = sph.id;\n this->mass = sph.mass; \n this->pos = sph.pos;\n this->meshornot = false;\n }\n\n void copyFromFP(const MeshData & mesh) {\n this->id = mesh.id;\n this->mass = mesh.mass; \n this->pos = mesh.pos;\n this->meshornot = true;\n }\n\n PS::F64vec getPos() const {\n return this->pos;\n }\n\n};\n\nclass PhysicsEPJ {\npublic:\n PS::S32 id;\n PS::F64 mass;\n PS::F64vec pos;\n PS::F64 ksr;\n PS::F64 hinv;\n PS::F64 dinv;\n PS::F64 temp;\n PS::F64 uene;\n bool meshornot;\n\n void copyFromFP(const SPHAnalysis & sph) {\n this->id = sph.id;\n this->mass = sph.mass; \n this->pos = sph.pos;\n this->ksr = sph.ksr;\n this->hinv = 1. / sph.ksr;\n this->dinv = 1. / sph.dens;\n this->temp = sph.temp;\n this->uene = sph.uene;\n this->meshornot = false;\n }\n\n void copyFromFP(const MeshData & mesh) {\n this->id = mesh.id;\n this->mass = mesh.mass; \n this->pos = mesh.pos;\n this->ksr = mesh.ksr;\n this->hinv = 1. / mesh.ksr;\n this->dinv = 1. / mesh.dens;\n this->temp = mesh.temp;\n this->uene = mesh.uene;\n this->meshornot = true;\n }\n\n PS::F64vec getPos() const {\n return this->pos;\n }\n\n PS::F64 getRSearch() const {\n return this->ksr;\n }\n\n void setPos(const PS::F64vec pos_new) {\n pos = pos_new;\n }\n};\n\nstruct calcPhysics {\n\n const PS::F64 ceff0 = +3.342253804929802286e+00;\n inline PS::F64 kernel0th(const PS::F64 r) {\n PS::F64 rmin = ((1. - r > 0.) ? (1. - r) : 0.);\n PS::F64 rmin2 = rmin * rmin;\n return ceff0 * rmin2 * rmin2 * (1. + 4. * r);\n }\n\n void operator () (const PhysicsEPI * epi,\n const PS::S32 nip,\n const PhysicsEPJ * epj,\n const PS::S32 njp,\n Physics * physics) {\n\n for(PS::S64 i = 0; i < nip; i++) {\n\n if(!epi[i].meshornot) {\n continue;\n }\n\n PS::F64 dens = 0.;\n PS::F64 temp = 0.;\n PS::F64 uene = 0.;\n\n for(PS::S64 j = 0; j < njp; j++) {\n PS::F64vec dx = epi[i].pos - epj[j].pos;\n PS::F64 r2 = dx * dx;\n PS::F64 r1 = sqrt(r2);\n PS::F64 q = r1 * epj[j].hinv;\n PS::F64 kw0 = kernel0th(q);\n PS::F64 hi3 = epj[j].hinv * epj[j].hinv * epj[j].hinv;\n\n PS::F64 densi = epj[j].mass * hi3 * kw0;\n PS::F64 tempi = epj[j].mass * hi3 * kw0 * epj[j].temp * epj[j].dinv;\n PS::F64 uenei = epj[j].mass * hi3 * kw0 * epj[j].uene * epj[j].dinv;\n dens += ((epj[j].mass != 0.) ? densi : 0.);\n temp += ((epj[j].mass != 0.) ? tempi : 0.);\n uene += ((epj[j].mass != 0.) ? uenei : 0.);\n }\n\n physics[i].dens = dens;\n physics[i].temp = temp;\n physics[i].uene = uene;\n }\n \n }\n\n};\n\ntemplate \nvoid calcMeshData(Tdinfo & dinfo,\n Tsph & sph,\n Tmesh & mesh,\n Tphysics & physics) {\n PS::MT::init_genrand(0);\n dinfo.decomposeDomainAll(sph);\n sph.exchangeParticle(dinfo);\n mesh.exchangeParticle(dinfo);\n physics.setParticleLocalTree(mesh);\n physics.setParticleLocalTree(sph, false);\n physics.calcForceMakingTree(calcPhysics(), dinfo);\n PS::S64 nmesh = mesh.getNumberOfParticleLocal();\n for(PS::S64 i = 0; i < nmesh; i++) {\n mesh[i].copyFromForce(physics.getForce(i));\n }\n for(PS::S64 i = 0; i < nmesh; i++) {\n NR::Nucleon cmps;\n cmps[1] = cmps[2] = 0.5;\n PS::F64 dens = mesh[i].dens;\n PS::F64 uene = mesh[i].uene;\n PS::F64 temp = mesh[i].temp;\n PS::F64 tout = 0.;\n PS::F64 pout, cout, sout;\n if(dens != 0.) {\n flash_helmholtz_(&dens, &uene, &temp, cmps.getPointer(),\n &pout, &cout, &tout, &sout);\n }\n mesh[i].tempu = tout;\n mesh[i].vsnd = sout;\n }\n}\n\ntemplate \nvoid shiftCenter(Tsph & sph,\n Tbhns & bhns) {\n PS::S64 nbhns = bhns.getNumberOfParticleLocal();\n PS::F64vec ploc = 0.;\n if(nbhns == 1) {\n ploc = bhns[0].pos;\n } else {\n ploc = 0.;\n }\n PS::F64vec pbhns = PS::Comm::getSum(ploc);\n\n for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n sph[i].pos -= pbhns;\n }\n}\n\nint main(int argc, char ** argv) {\n PS::Initialize(argc, argv);\n\n init_flash_helmholtz_(&CodeUnit::FractionOfCoulombCorrection);\n\n PS::DomainInfo dinfo;\n dinfo.initialize();\n PS::ParticleSystem sph;\n sph.initialize();\n sph.createParticle(0);\n sph.setNumberOfParticleLocal(0);\n PS::ParticleSystem bhns;\n bhns.initialize();\n bhns.createParticle(0);\n bhns.setNumberOfParticleLocal(0);\n PS::ParticleSystem mesh;\n mesh.initialize();\n mesh.createParticle(0);\n mesh.setNumberOfParticleLocal(0);\n PS::TreeForForceShort::Scatter physics;\n physics.initialize(0);\n\n if(PS::Comm::getRank() == 0) {\n printf(\"AT comments: NPROCESS %8d\\n\", PS::Comm::getNumberOfProc());\n printf(\"AT comments: NTHREAD %8d\\n\", PS::Comm::getNumberOfThread());\n }\n\n char idir[1024], otype[1024];\n PS::S64 ibgn, iend;\n FILE * fp = fopen(argv[1], \"r\");\n fscanf(fp, \"%s\", idir);\n fscanf(fp, \"%s\", otype);\n fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n fclose(fp);\n\n generateMeshData(mesh);\n\n for(PS::S64 itime = ibgn; itime <= iend; itime++) {\n char sfile[1024], bfile[1024];\n sprintf(sfile, \"%s/sph_t%04d.dat\", idir, itime);\n sprintf(bfile, \"%s/bhns_t%04d.dat\", idir, itime);\n fp = fopen(sfile, \"r\");\n if(fp == NULL) {\n continue;\n }\n sph.readParticleAscii(sfile);\n fclose(fp);\n fp = fopen(bfile, \"r\");\n if(fp == NULL) {\n continue;\n }\n bhns.readParticleAscii(bfile);\n fclose(fp);\n\n shiftCenter(sph, bhns);\n calcMeshData(dinfo, sph, mesh, physics);\n\n char ofile[1024];\n sprintf(ofile, \"%s_t%04d.dat\", otype, itime);\n mesh.writeParticleAscii(ofile);\n }\n\n PS::Finalize();\n\n return 0;\n}\n", "meta": {"hexsha": "589d47f79e53d9d02ca0602994975d980a456f46", "size": 13375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.nswd/calc_hotspot/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.nswd/calc_hotspot/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool.nswd/calc_hotspot/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 29.5253863135, "max_line_length": 89, "alphanum_fraction": 0.484635514, "num_tokens": 4376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1986387217261371}} {"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DeterminantAndInverse.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Structure/Side.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/NormalCovectorAndMagnitude.hpp\"\n#include \"Evolution/Systems/GeneralizedHarmonic/Tags.hpp\"\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.tpp\"\n#include \"Evolution/Systems/GrMhd/GhValenciaDivClean/System.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Tags.hpp\"\n#include \"NumericalAlgorithms/FiniteDifference/MonotisedCentral.hpp\"\n#include \"NumericalAlgorithms/FiniteDifference/Unlimited.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Lapse.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Shift.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/SpatialMetric.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace grmhd::GhValenciaDivClean::fd {\nMonotisedCentralPrim::MonotisedCentralPrim(CkMigrateMessage* const msg)\n : Reconstructor(msg) {}\n\nstd::unique_ptr MonotisedCentralPrim::get_clone() const {\n return std::make_unique(*this);\n}\n\nvoid MonotisedCentralPrim::pup(PUP::er& p) { Reconstructor::pup(p); }\n\n// NOLINTNEXTLINE\nPUP::able::PUP_ID MonotisedCentralPrim::my_PUP_ID = 0;\n\ntemplate \nvoid MonotisedCentralPrim::reconstruct(\n const gsl::not_null, dim>*>\n vars_on_lower_face,\n const gsl::not_null, dim>*>\n vars_on_upper_face,\n const Variables>& volume_prims,\n const Variables&\n volume_spacetime_and_cons_vars,\n const EquationsOfState::EquationOfState& eos,\n const Element& element,\n const FixedHashMap<\n maximum_number_of_neighbors(dim) + 1,\n std::pair, ElementId>, std::vector,\n boost::hash, ElementId>>>& neighbor_data,\n const Mesh& subcell_mesh) const {\n reconstruct_prims_work>>(\n vars_on_lower_face, vars_on_upper_face,\n [](auto upper_face_vars_ptr, auto lower_face_vars_ptr,\n const auto& volume_vars, const auto& ghost_cell_vars,\n const auto& subcell_extents, const size_t number_of_variables) {\n ::fd::reconstruction::monotised_central(\n upper_face_vars_ptr, lower_face_vars_ptr, volume_vars,\n ghost_cell_vars, subcell_extents, number_of_variables);\n },\n [](auto upper_face_vars_ptr, auto lower_face_vars_ptr,\n const auto& volume_vars, const auto& ghost_cell_vars,\n const auto& subcell_extents, const size_t number_of_variables) {\n ::fd::reconstruction::unlimited<2>(\n upper_face_vars_ptr, lower_face_vars_ptr, volume_vars,\n ghost_cell_vars, subcell_extents, number_of_variables);\n },\n [](const auto vars_on_face_ptr) {\n const auto& spacetime_metric =\n get>(*vars_on_face_ptr);\n auto& spatial_metric =\n get>(*vars_on_face_ptr);\n gr::spatial_metric(make_not_null(&spatial_metric), spacetime_metric);\n auto& inverse_spatial_metric =\n get>(*vars_on_face_ptr);\n auto& sqrt_det_spatial_metric =\n get>(*vars_on_face_ptr);\n\n determinant_and_inverse(make_not_null(&sqrt_det_spatial_metric),\n make_not_null(&inverse_spatial_metric),\n spatial_metric);\n get(sqrt_det_spatial_metric) = sqrt(get(sqrt_det_spatial_metric));\n\n auto& shift = get>(*vars_on_face_ptr);\n gr::shift(make_not_null(&shift), spacetime_metric,\n inverse_spatial_metric);\n gr::lapse(make_not_null(&get>(*vars_on_face_ptr)),\n shift, spacetime_metric);\n },\n volume_prims, volume_spacetime_and_cons_vars, eos, element, neighbor_data,\n subcell_mesh, ghost_zone_size());\n}\n\ntemplate \nvoid MonotisedCentralPrim::reconstruct_fd_neighbor(\n const gsl::not_null*> vars_on_face,\n const Variables>& subcell_volume_prims,\n const Variables, GeneralizedHarmonic::Tags::Phi<3>,\n GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_metric,\n const EquationsOfState::EquationOfState& eos,\n const Element& element,\n const FixedHashMap<\n maximum_number_of_neighbors(dim) + 1,\n std::pair, ElementId>, std::vector,\n boost::hash, ElementId>>>& neighbor_data,\n const Mesh& subcell_mesh,\n const Direction direction_to_reconstruct) const {\n reconstruct_fd_neighbor_work(\n vars_on_face,\n [](const auto tensor_component_on_face_ptr,\n const auto& tensor_component_volume,\n const auto& tensor_component_neighbor,\n const Index& subcell_extents,\n const Index& ghost_data_extents,\n const Direction& local_direction_to_reconstruct) {\n ::fd::reconstruction::reconstruct_neighbor<\n Side::Lower,\n ::fd::reconstruction::detail::MonotisedCentralReconstructor>(\n tensor_component_on_face_ptr, tensor_component_volume,\n tensor_component_neighbor, subcell_extents, ghost_data_extents,\n local_direction_to_reconstruct);\n },\n [](const auto tensor_component_on_face_ptr,\n const auto& tensor_component_volume,\n const auto& tensor_component_neighbor,\n const Index& subcell_extents,\n const Index& ghost_data_extents,\n const Direction& local_direction_to_reconstruct) {\n ::fd::reconstruction::reconstruct_neighbor<\n Side::Lower,\n ::fd::reconstruction::detail::UnlimitedReconstructor<2>>(\n tensor_component_on_face_ptr, tensor_component_volume,\n tensor_component_neighbor, subcell_extents, ghost_data_extents,\n local_direction_to_reconstruct);\n },\n [](const auto tensor_component_on_face_ptr,\n const auto& tensor_component_volume,\n const auto& tensor_component_neighbor,\n const Index& subcell_extents,\n const Index& ghost_data_extents,\n const Direction& local_direction_to_reconstruct) {\n ::fd::reconstruction::reconstruct_neighbor<\n Side::Upper,\n ::fd::reconstruction::detail::MonotisedCentralReconstructor>(\n tensor_component_on_face_ptr, tensor_component_volume,\n tensor_component_neighbor, subcell_extents, ghost_data_extents,\n local_direction_to_reconstruct);\n },\n [](const auto tensor_component_on_face_ptr,\n const auto& tensor_component_volume,\n const auto& tensor_component_neighbor,\n const Index& subcell_extents,\n const Index& ghost_data_extents,\n const Direction& local_direction_to_reconstruct) {\n ::fd::reconstruction::reconstruct_neighbor<\n Side::Upper,\n ::fd::reconstruction::detail::UnlimitedReconstructor<2>>(\n tensor_component_on_face_ptr, tensor_component_volume,\n tensor_component_neighbor, subcell_extents, ghost_data_extents,\n local_direction_to_reconstruct);\n },\n [](const auto vars_on_face_ptr) {\n const auto& spacetime_metric =\n get>(*vars_on_face_ptr);\n auto& spatial_metric =\n get>(*vars_on_face_ptr);\n gr::spatial_metric(make_not_null(&spatial_metric), spacetime_metric);\n auto& inverse_spatial_metric =\n get>(*vars_on_face_ptr);\n auto& sqrt_det_spatial_metric =\n get>(*vars_on_face_ptr);\n\n determinant_and_inverse(make_not_null(&sqrt_det_spatial_metric),\n make_not_null(&inverse_spatial_metric),\n spatial_metric);\n get(sqrt_det_spatial_metric) = sqrt(get(sqrt_det_spatial_metric));\n\n auto& shift = get>(*vars_on_face_ptr);\n gr::shift(make_not_null(&shift), spacetime_metric,\n inverse_spatial_metric);\n gr::lapse(make_not_null(&get>(*vars_on_face_ptr)),\n shift, spacetime_metric);\n },\n subcell_volume_prims, subcell_volume_spacetime_metric, eos, element,\n neighbor_data, subcell_mesh, direction_to_reconstruct, ghost_zone_size());\n}\n\nbool operator==(const MonotisedCentralPrim& /*lhs*/,\n const MonotisedCentralPrim& /*rhs*/) {\n return true;\n}\n\nbool operator!=(const MonotisedCentralPrim& lhs,\n const MonotisedCentralPrim& rhs) {\n return not(lhs == rhs);\n}\n\n#define THERMO_DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define TAGS_LIST(data) \\\n tmpl::list< \\\n gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Pi<3>, \\\n GeneralizedHarmonic::Tags::Phi<3>, ValenciaDivClean::Tags::TildeD, \\\n ValenciaDivClean::Tags::TildeTau, \\\n ValenciaDivClean::Tags::TildeS, \\\n ValenciaDivClean::Tags::TildeB, \\\n ValenciaDivClean::Tags::TildePhi, \\\n hydro::Tags::RestMassDensity, \\\n hydro::Tags::SpecificInternalEnergy, \\\n hydro::Tags::SpatialVelocity, \\\n hydro::Tags::MagneticField, \\\n hydro::Tags::DivergenceCleaningField, \\\n hydro::Tags::LorentzFactor, \\\n hydro::Tags::Pressure, \\\n hydro::Tags::SpecificEnthalpy, \\\n hydro::Tags::LorentzFactorTimesSpatialVelocity, \\\n ::Tags::Flux, \\\n Frame::Inertial>, \\\n ::Tags::Flux, \\\n Frame::Inertial>, \\\n ::Tags::Flux, \\\n tmpl::size_t<3>, Frame::Inertial>, \\\n ::Tags::Flux, \\\n tmpl::size_t<3>, Frame::Inertial>, \\\n ::Tags::Flux, \\\n Frame::Inertial>, \\\n gr::Tags::Lapse<>, gr::Tags::Shift<3, Frame::Inertial, DataVector>, \\\n gr::Tags::SpatialMetric<3>, gr::Tags::SqrtDetSpatialMetric, \\\n gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>, \\\n evolution::dg::Actions::detail::NormalVector<3>>\n\n#define INSTANTIATION(r, data) \\\n template void MonotisedCentralPrim::reconstruct( \\\n gsl::not_null, 3>*> \\\n vars_on_lower_face, \\\n gsl::not_null, 3>*> \\\n vars_on_upper_face, \\\n const Variables>& volume_prims, \\\n const Variables& \\\n volume_spacetime_and_cons_vars, \\\n const EquationsOfState::EquationOfState& eos, \\\n const Element<3>& element, \\\n const FixedHashMap< \\\n maximum_number_of_neighbors(3) + 1, \\\n std::pair, ElementId<3>>, std::vector, \\\n boost::hash, ElementId<3>>>>& neighbor_data, \\\n const Mesh<3>& subcell_mesh) const; \\\n template void MonotisedCentralPrim::reconstruct_fd_neighbor( \\\n gsl::not_null*> vars_on_face, \\\n const Variables>& subcell_volume_prims, \\\n const Variables, GeneralizedHarmonic::Tags::Phi<3>, \\\n GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_metric, \\\n const EquationsOfState::EquationOfState& eos, \\\n const Element<3>& element, \\\n const FixedHashMap< \\\n maximum_number_of_neighbors(3) + 1, \\\n std::pair, ElementId<3>>, std::vector, \\\n boost::hash, ElementId<3>>>>& neighbor_data, \\\n const Mesh<3>& subcell_mesh, \\\n const Direction<3> direction_to_reconstruct) const;\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2))\n\n#undef INSTANTIATION\n#undef TAGS_LIST\n#undef THERMO_DIM\n} // namespace grmhd::GhValenciaDivClean::fd\n", "meta": {"hexsha": "3f40e657f84b7eff37f84db44a4aae8bbfda46b6", "size": 15264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.cpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/MonotisedCentral.cpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 52.8166089965, "max_line_length": 91, "alphanum_fraction": 0.6326650943, "num_tokens": 3431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.19851793966029452}} {"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp\n//! \\author Alex Robinson, Eli Moll\n//! \\brief Tet mesh flux estimator class declaration.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n#define MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n\n// Std Lib Includes\n#include \n\n// Boost Includes\n#include \n#include \n#include \n\n// Moab Includes\n#include \n#include \n#include \n\n// Trilinos Includes\n#include \n\n// FRENSIE Includes\n#include \"MonteCarlo_StandardEntityEstimator.hpp\"\n#include \"MonteCarlo_ParticleSubtrackEndingGlobalEventObserver.hpp\"\n#include \"MonteCarlo_EstimatorContributionMultiplierPolicy.hpp\"\n#include \"Geometry_ModuleTraits.hpp\"\n#include \"MonteCarlo_ParticleState.hpp\"\n\nnamespace MonteCarlo{\n\n/*! The tet-mesh track length flux estimator class\n * \\details This class is based off of the TrackLengthMeshTally written by\n * Kerry Dunn (UW-Madison CNERG group). The DAGMC repo that contains her\n * class can be found at https://github.com/svalinn/DAGMC.\n */\ntemplate\nclass TetMeshTrackLengthFluxEstimator : public StandardEntityEstimator,\n public ParticleSubtrackEndingGlobalEventObserver\n{\n\npublic:\n\n //! Typedef for the cell id type\n typedef Geometry::ModuleTraits::InternalCellHandle cellIdType;\n\n //! Typedef for event tags used for quick dispatcher registering\n typedef boost::mpl::vector\n EventTags;\n\n //! Constructor\n TetMeshTrackLengthFluxEstimator(\n\t\t const Estimator::idType id,\n\t\t const double multiplier,\n\t\t const std::string input_mesh_file_name,\n\t\t const std::string output_mesh_file_name = \"tetmesh.h5m\" );\n\n //! Destructor\n ~TetMeshTrackLengthFluxEstimator()\n { /* ... */ }\n\n //! Set the response functions\n void setResponseFunctions(\n const Teuchos::Array >& response_functions );\n\n //! Set the particle types that can contribute to the estimator\n void setParticleTypes( const Teuchos::Array& particle_types );\n\n //! Add current history estimator contribution\n void updateFromGlobalParticleSubtrackEndingEvent(\n\t\t\t\t\t\t const ParticleState& particle,\n\t\t\t\t\t\t const double start_point[3],\n\t\t\t\t\t\t const double end_point[3] );\n\n //! Export the estimator data\n void exportData( EstimatorHDF5FileHandler& hdf5_file,\n\t\t const bool process_data ) const;\n\n //! Print the estimator data\n void print( std::ostream& os ) const;\n\n //! Get all tet elements\n const moab::Range getAllTetElements() const;\n\n //! Test if a point is in the mesh\n bool isPointInMesh( const double point[3] );\n\n //! Determine which tet the point is in\n moab::EntityHandle whichTetIsPointIn( const double point[3] );\n\nprivate:\n\n // Assign bin boundaries to an estimator dimension\n void assignBinBoundaries(\n\tconst Teuchos::RCP& bin_boundaries );\n\n // The tolerance used for geometric tests\n static const double s_tol;\n\n // The moab instance that stores all mesh data\n Teuchos::RCP d_moab_interface;\n\n // The tet meshset\n moab::EntityHandle d_tet_meshset;\n\n // The kd-tree for finding point in tet\n Teuchos::RCP d_kd_tree;\n \n // The root of the kd-tree\n moab::EntityHandle d_kd_tree_root;\n\n // The map of tet ids and barycentric coordinate transform matrices\n boost::unordered_map \n d_tet_barycentric_transform_matrices;\n \n // The map of tet ids and reference vertices\n boost::unordered_map\n d_tet_reference_vertices;\n \n // The output mesh file name\n std::string d_output_mesh_name;\n};\n \n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_TetMeshTrackLengthFluxEstimator_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_TET_MESH_TRACK_LENGTH_FLUX_ESTIMATOR_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "294b61772bf05017a1711d9de37f7680a1d53644", "size": 4660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp", "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/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp", "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/monte_carlo/estimator/native/src/MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp", "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": 32.3611111111, "max_line_length": 91, "alphanum_fraction": 0.6770386266, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19805170031997832}} {"text": "#include \n\n#include \"gflags/gflags.h\"\n#include \"sndfile.h\"\n#include \"tbb/tbb.h\"\n#include \"tbb/pipeline.h\"\n#include \"tbb/scalable_allocator.h\"\n#include \"tbb/cache_aligned_allocator.h\"\n#include \n#include \n#include \"bakuage/sndfile_wrapper.h\"\n#include \"bakuage/dft.h\"\n#include \"bakuage/memory.h\"\n#include \"bakuage/utils.h\"\n#include \"bakuage/window_func.h\"\n#include \"bakuage/transient_filter.h\"\n#include \"bakuage/transient_filter2.h\"\n\nDEFINE_string(input, \"\", \"comma separated input wav file paths\");\nDEFINE_string(output, \"\", \"output wav file path\");\nDEFINE_double(window_sec, 0.02, \"dft window size in sec\");\nDEFINE_double(mean_sec, 0.02, \"energy lowpass mean time in sec\");\nDEFINE_double(ratio, 2, \"ratio\");\nDEFINE_double(noise_reduction_threshold, -20, \"noise reduction threshold in dB\");\nDEFINE_bool(normalize, false, \"whether if normalize is done before output\");\nDEFINE_string(mode, \"transient\", \"mode (transient)\");\n\nnamespace {\ntypedef float Float;\n \ntemplate \nvoid CalculateEffect(Effect *effect, const std::vector> &input, int channels, int samples, int sample_freq, Float *output) {\n\n std::cerr << \"calculate start\" << std::endl;\n bakuage::StopWatch stop_watch;\n stop_watch.Start();\n Float temp[2] = { 0 };\n Float zero[2] = { 0 };\n for (int i = 0; i < samples + effect->delay_samples(); i++) {\n if (i < samples) {\n for (int j = 0; j < channels; j++) {\n temp[j] = input[0][channels * i + j];\n }\n effect->Clock(temp, temp);\n } else {\n effect->Clock(zero, temp);\n }\n \n int output_i = i - effect->delay_samples();\n if (0 <= output_i) {\n for (int j = 0; j < channels; j++) {\n output[channels * output_i + j] = temp[j];\n }\n }\n }\n \n std::cerr << \"calculate finish \" << stop_watch.time() << std::endl;\n}\n\ntemplate \nvoid SaveFloatWave(const std::vector &wave, const std::string &filename) {\n bakuage::SndfileWrapper snd_file;\n SF_INFO sfinfo = { 0 };\n std::memset(&sfinfo, 0, sizeof(sfinfo));\n \n sfinfo.channels = 2;\n sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;\n int frames = wave.size() / sfinfo.channels;\n sfinfo.frames = frames;\n sfinfo.samplerate = 44100;\n \n if ((snd_file.set(sf_open(filename.c_str(), SFM_WRITE, &sfinfo))) == NULL) {\n std::stringstream message;\n message << \"Not able to open output file \" << filename << \", \"\n << sf_strerror(NULL);\n throw std::logic_error(message.str());\n }\n \n sf_count_t size;\n if (sizeof(Float) == 4) {\n size = sf_writef_float(snd_file.get(), (float *)wave.data(), frames);\n } else {\n size = sf_writef_double(snd_file.get(), (double *)wave.data(), frames);\n }\n if (size != frames) {\n std::stringstream message;\n message << \"sf_writef_float error: \" << size;\n throw std::logic_error(message.str());\n }\n}\n}\n\n// wavを受け取って、標準出力にrawvideoを出力\nint main(int argc, char* argv[]) {\n gflags::SetVersionString(\"1.0.0\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n \n bakuage::SndfileWrapper infile;\n SF_INFO sfinfo = { 0 };\n int frames = 1 << 30;\n \n // カンマ区切りを分解して、load wave (全てが同じフォーマットである必要がある)\n std::vector> buffers;\n std::vector input_paths;\n boost::algorithm::split(input_paths, FLAGS_input, boost::is_any_of(\",\"));\n for (const auto &input_file_path: input_paths) {\n if ((infile.set(sf_open (input_file_path.c_str(), SFM_READ, &sfinfo))) == NULL) {\n fprintf(stderr, \"Not able to open input file %s.\\n\", input_file_path.c_str());\n fprintf(stderr, \"%s\\n\", sf_strerror(NULL));\n return 1;\n }\n \n // check format\n fprintf(stderr, \"sfinfo.format 0x%08x.\\n\", sfinfo.format);\n switch (sfinfo.format & SF_FORMAT_TYPEMASK) {\n case SF_FORMAT_WAV:\n case SF_FORMAT_WAVEX:\n break;\n default:\n fprintf(stderr, \"Not supported sfinfo.format 0x%08x.\\n\", sfinfo.format);\n return 2;\n }\n \n std::vector buffer(sfinfo.channels * sfinfo.frames);\n int read_size = sf_readf_float(infile.get(), buffer.data(), sfinfo.frames);\n fprintf(stderr, \"%d samples read.\\n\", read_size);\n if (read_size != sfinfo.frames) {\n fprintf(stderr, \"sf_readf_float error: %d %d\\n\", read_size, (int)sfinfo.frames);\n return 3;\n }\n buffers.emplace_back(buffer);\n \n frames = std::min(frames, sfinfo.frames);\n }\n \n // calculate spectrogram (energy)\n std::vector output(frames * sfinfo.channels);\n \n if (FLAGS_mode == \"transient\") {\n bakuage::TransientFilter>::Config config;\n config.num_channels = sfinfo.channels;\n config.sample_rate = sfinfo.samplerate;\n config.long_mean_sec = 0.2;\n config.short_mean_sec = 0.02;\n config.gain_func = [](Float long_loundess, Float short_loudness) {\n return (short_loudness - long_loundess) * (FLAGS_ratio - 1);\n };\n bakuage::TransientFilter> transient_filter(config);\n CalculateEffect(&transient_filter, buffers, sfinfo.channels, frames, sfinfo.samplerate, output.data());\n } else if (FLAGS_mode == \"transient2\") {\n bakuage::TransientFilter2>::Config config;\n config.num_channels = sfinfo.channels;\n config.sample_rate = sfinfo.samplerate;\n config.long_mean_sec = 0.2;\n config.short_mean_sec = 0.02;\n config.gain_func = [](Float long_loundess, Float short_loudness) {\n return (short_loudness - long_loundess) * (FLAGS_ratio - 1);\n };\n bakuage::TransientFilter2> transient_filter(config);\n CalculateEffect(&transient_filter, buffers, sfinfo.channels, frames, sfinfo.samplerate, output.data());\n }\n \n // normalize\n if (FLAGS_normalize) {\n double peak = 1e-37;\n for (int i = 0; i < output.size(); i++) {\n peak = std::max(peak, std::abs(output[i]));\n }\n for (int i = 0; i < output.size(); i++) {\n output[i] /= peak;\n }\n }\n \n // save output\n SaveFloatWave(output, FLAGS_output);\n}\n\n", "meta": {"hexsha": "51ade6db1a504cc615d5f8eb82eebf87ef78ac6d", "size": 6601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/effect_test/main.cpp", "max_stars_repo_name": "nankasuisui/phaselimiter", "max_stars_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:43:47.000Z", "max_issues_repo_path": "src/effect_test/main.cpp", "max_issues_repo_name": "nankasuisui/phaselimiter", "max_issues_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/effect_test/main.cpp", "max_forks_repo_name": "nankasuisui/phaselimiter", "max_forks_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-03T13:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T20:21:10.000Z", "avg_line_length": 37.0842696629, "max_line_length": 143, "alphanum_fraction": 0.6156642933, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.34510525748676857, "lm_q1q2_score": 0.19797943451849767}} {"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#ifndef BOOST_GRAPH_DIJKSTRA_HPP\n#define BOOST_GRAPH_DIJKSTRA_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n# include \n#endif // BOOST_GRAPH_DIJKSTRA_TESTING\n\nnamespace boost {\n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n static bool dijkstra_relaxed_heap = true;\n#endif\n\n template \n struct DijkstraVisitorConcept {\n void constraints() {\n function_requires< CopyConstructibleConcept >();\n vis.initialize_vertex(u, g);\n vis.discover_vertex(u, g);\n vis.examine_vertex(u, g);\n vis.examine_edge(e, g);\n vis.edge_relaxed(e, g);\n vis.edge_not_relaxed(e, g);\n vis.finish_vertex(u, g);\n }\n Visitor vis;\n Graph g;\n typename graph_traits::vertex_descriptor u;\n typename graph_traits::edge_descriptor e;\n };\n\n template \n class dijkstra_visitor : public bfs_visitor {\n public:\n dijkstra_visitor() { }\n dijkstra_visitor(Visitors vis)\n : bfs_visitor(vis) { }\n\n template \n void edge_relaxed(Edge e, Graph& g) {\n invoke_visitors(this->m_vis, e, g, on_edge_relaxed());\n }\n template \n void edge_not_relaxed(Edge e, Graph& g) {\n invoke_visitors(this->m_vis, e, g, on_edge_not_relaxed());\n }\n private:\n template \n void tree_edge(Edge u, Graph& g) { }\n };\n template \n dijkstra_visitor\n make_dijkstra_visitor(Visitors vis) {\n return dijkstra_visitor(vis);\n }\n typedef dijkstra_visitor<> default_dijkstra_visitor;\n\n namespace detail {\n\n template \n struct dijkstra_bfs_visitor\n {\n typedef typename property_traits::value_type D;\n\n dijkstra_bfs_visitor(UniformCostVisitor vis, UpdatableQueue& Q,\n WeightMap w, PredecessorMap p, DistanceMap d,\n BinaryFunction combine, BinaryPredicate compare,\n D zero)\n : m_vis(vis), m_Q(Q), m_weight(w), m_predecessor(p), m_distance(d),\n m_combine(combine), m_compare(compare), m_zero(zero) { }\n\n template \n void tree_edge(Edge e, Graph& g) {\n m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n m_combine, m_compare);\n if (m_decreased)\n m_vis.edge_relaxed(e, g);\n else\n m_vis.edge_not_relaxed(e, g);\n }\n template \n void gray_target(Edge e, Graph& g) {\n m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n m_combine, m_compare);\n if (m_decreased) {\n m_Q.update(target(e, g));\n m_vis.edge_relaxed(e, g);\n } else\n m_vis.edge_not_relaxed(e, g);\n }\n\n template \n void initialize_vertex(Vertex /*u*/, Graph& /*g*/) { }\n template \n void non_tree_edge(Edge, Graph&) { }\n template \n void discover_vertex(Vertex u, Graph& g) { m_vis.discover_vertex(u, g); }\n template \n void examine_vertex(Vertex u, Graph& g) { m_vis.examine_vertex(u, g); }\n template \n void examine_edge(Edge e, Graph& g) {\n if (m_compare(get(m_weight, e), m_zero))\n throw negative_edge();\n m_vis.examine_edge(e, g);\n }\n template \n void black_target(Edge, Graph&) { }\n template \n void finish_vertex(Vertex u, Graph& g) { m_vis.finish_vertex(u, g); }\n\n UniformCostVisitor m_vis;\n UpdatableQueue& m_Q;\n WeightMap m_weight;\n PredecessorMap m_predecessor;\n DistanceMap m_distance;\n BinaryFunction m_combine;\n BinaryPredicate m_compare;\n bool m_decreased;\n D m_zero;\n };\n\n } // namespace detail\n\n // Call breadth first search with default color map.\n template \n inline void\n dijkstra_shortest_paths_no_init\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n IndexMap index_map,\n Compare compare, Combine combine, DistZero zero,\n DijkstraVisitor vis)\n {\n std::vector color(num_vertices(g));\n default_color_type c = white_color;\n dijkstra_shortest_paths_no_init( g, s, predecessor, distance, weight,\n index_map, compare, combine, zero, vis,\n make_iterator_property_map(&color[0], index_map, c));\n }\n\n // Call breadth first search\n template \n inline void\n dijkstra_shortest_paths_no_init\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n IndexMap index_map,\n Compare compare, Combine combine, DistZero zero,\n DijkstraVisitor vis, ColorMap color)\n {\n typedef indirect_cmp IndirectCmp;\n IndirectCmp icmp(distance, compare);\n\n typedef typename graph_traits::vertex_descriptor Vertex;\n\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\n if (!dijkstra_relaxed_heap) {\n typedef mutable_queue, IndirectCmp, IndexMap>\n MutableQueue;\n\n MutableQueue Q(num_vertices(g), icmp, index_map);\n\n detail::dijkstra_bfs_visitor\n bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\n\n breadth_first_visit(g, s, Q, bfs_vis, color);\n return;\n }\n#endif // BOOST_GRAPH_DIJKSTRA_TESTING\n\n typedef relaxed_heap MutableQueue;\n\n MutableQueue Q(num_vertices(g), icmp, index_map);\n\n detail::dijkstra_bfs_visitor\n bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\n\n breadth_first_visit(g, s, Q, bfs_vis, color);\n }\n\n // Initialize distances and call breadth first search with default color map\n template \n inline void\n dijkstra_shortest_paths\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n IndexMap index_map,\n Compare compare, Combine combine, DistInf inf, DistZero zero,\n DijkstraVisitor vis)\n {\n std::vector color(num_vertices(g));\n default_color_type c = white_color;\n dijkstra_shortest_paths(g, s, predecessor, distance, weight, index_map,\n compare, combine, inf, zero, vis,\n make_iterator_property_map(&color[0], index_map,\n c));\n }\n\n // Initialize distances and call breadth first search\n template \n inline void\n dijkstra_shortest_paths\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n IndexMap index_map,\n Compare compare, Combine combine, DistInf inf, DistZero zero,\n DijkstraVisitor vis, ColorMap color)\n {\n typedef typename property_traits::value_type ColorValue;\n typedef color_traits Color;\n typename graph_traits::vertex_iterator ui, ui_end;\n for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n vis.initialize_vertex(*ui, g);\n put(distance, *ui, inf);\n put(predecessor, *ui, *ui);\n put(color, *ui, Color::white());\n }\n put(distance, s, zero);\n\n dijkstra_shortest_paths_no_init(g, s, predecessor, distance, weight,\n index_map, compare, combine, zero, vis, color);\n }\n\n namespace detail {\n\n // Handle defaults for PredecessorMap and\n // Distance Compare, Combine, Inf and Zero\n template \n inline void\n dijkstra_dispatch2\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n DistanceMap distance, WeightMap weight, IndexMap index_map,\n const Params& params, ColorMap color)\n {\n // Default for predecessor map\n dummy_property_map p_map;\n\n typedef typename property_traits::value_type D;\n dijkstra_shortest_paths\n (g, s,\n choose_param(get_param(params, vertex_predecessor), p_map),\n distance, weight, index_map,\n choose_param(get_param(params, distance_compare_t()),\n std::less()),\n choose_param(get_param(params, distance_combine_t()),\n closed_plus()),\n choose_param(get_param(params, distance_inf_t()),\n (std::numeric_limits::max)()),\n choose_param(get_param(params, distance_zero_t()),\n D()),\n choose_param(get_param(params, graph_visitor),\n make_dijkstra_visitor(null_visitor())),\n color);\n }\n\n template \n inline void\n dijkstra_dispatch1\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n DistanceMap distance, WeightMap weight, IndexMap index_map,\n const Params& params, ColorMap color)\n {\n // Default for distance map\n typedef typename property_traits::value_type D;\n typename std::vector::size_type\n n = is_default_param(distance) ? num_vertices(g) : 1;\n std::vector distance_map(n);\n\n // Default for color map\n typename std::vector::size_type\n m = is_default_param(color) ? num_vertices(g) : 1;\n std::vector color_map(m);\n\n detail::dijkstra_dispatch2\n (g, s, choose_param(distance, make_iterator_property_map\n (distance_map.begin(), index_map,\n distance_map[0])),\n weight, index_map, params,\n choose_param(color, make_iterator_property_map\n (color_map.begin(), index_map,\n color_map[0])));\n }\n } // namespace detail\n\n // Named Parameter Variant\n template \n inline void\n dijkstra_shortest_paths\n (const VertexListGraph& g,\n typename graph_traits::vertex_descriptor s,\n const bgl_named_params& params)\n {\n // Default for edge weight and vertex index map is to ask for them\n // from the graph. Default for the visitor is null_visitor.\n detail::dijkstra_dispatch1\n (g, s,\n get_param(params, vertex_distance),\n choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\n params,\n get_param(params, vertex_color));\n }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_DIJKSTRA_HPP\n", "meta": {"hexsha": "243b17f752bca872f08e5b23fe67c799698a5f98", "size": 13156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/dijkstra_shortest_paths.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": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/dijkstra_shortest_paths.hpp", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/dijkstra_shortest_paths.hpp", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 37.8045977011, "max_line_length": 79, "alphanum_fraction": 0.6692763758, "num_tokens": 3046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.1977009496470258}} {"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n// /Doc/openOR_free_license.txt or\n// /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//! OPENOR_INTERFACE_FILE(openOR_core)\n//****************************************************************************\n/**\n * @file\n * @author Christian Winne\n * @ingroup openOR_core\n */\n\n#ifndef openOR_core_Math_matrixconcept_hpp\n#define openOR_core_Math_matrixconcept_hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace openOR {\n namespace Math {\n\n template \n typename if_const < P,\n typename MatrixTraits::type>::Access::ConstAccessType,\n typename MatrixTraits::type>::Access::AccessType > \n ::type get(P& p) {\n return MatrixTraits::type>::Access::template get(p);\n }\n\n\n namespace Impl {\n\n\n template < class Mat,\n int BeginRow = 0,\n int EndRow = MatrixTraits::RowDimension::value,\n int BeginCol = 0,\n int EndCol = MatrixTraits::ColDimension::value >\n class MatrixCompileTimeIterator {\n static const int SizeRow = EndRow - BeginRow;\n static const int SizeCol = EndCol - BeginCol;\n\n public:\n\n template class Op>\n inline void apply() const {\n BOOST_MPL_ASSERT((boost::mpl::less_equal, boost::mpl::int_ >));\n BOOST_MPL_ASSERT((boost::mpl::less_equal, boost::mpl::int_ >));\n Apply0<0, SizeRow * SizeCol, Op>()();\n }\n\n template class Op, class Mat2>\n inline void apply(Mat& mat, const Mat2& mat2) {\n BOOST_MPL_ASSERT((boost::mpl::less_equal, boost::mpl::int_ >));\n BOOST_MPL_ASSERT((boost::mpl::less_equal, boost::mpl::int_ >));\n Apply2<0, SizeRow * SizeCol, Op, Mat2>()(mat, mat2);\n }\n\n template